Mongoose 错误:已执行查询:

olhwl3o2  于 2022-11-13  发布在  Go
关注(0)|答案(2)|浏览(184)

I'm trying to update the document but the error says the query has already been executed.

  • MongooseError: Query was already executed: footballs.updateOne({ date: 'January 4' }, {})*
app.post('/api/bookslot', async (req, res) => {
  console.log(req.body);
  try {
    const token = req.headers['x-access-token'];
    const decoded = jwt.verify(token, 'secret123');
    const email = decoded.email;
    const user = await UserModel.findOne({ email: email });

    let sportname = req.body.selectedSport.toLowerCase();
    const time = req.body.slotTime;
    const seats = req.body.availableSeats - 1;

    if (!sportname.endsWith('s')) {
      sportname = sportname.concat('s');
    }
    const NewSlotModel = mongoose.model(sportname, slotSchema);
    var update = {};
    update[time] = seats - 1;
    console.log(update);
    const a = await NewSlotModel.updateOne(
      { date: req.body.slotDate },
      { $set: update },
      function (err, success) {
        if (err) return handleError(err);
      }
    );

    return res.json({ status: 'ok' });
  } catch (e) {
    console.log(e);
    res.json({ status: 'error' });
  }
});

where am I going wrong?

enyaitl3

enyaitl31#

您在代码中同时使用了async/await和回调,导致mongoose抛出错误。同时使用它们的实际效果就是您收到的错误类型:
已执行查询
Mongoose v6不允许重复查询。
Mongoose不再允许执行同一个查询对象两次。如果你这样做,你会得到一个Query was already executed错误。执行同一个查询示例两次通常意味着混合了回调和承诺,但是如果你需要执行同一个查询两次,你可以调用Query#clone()来克隆查询并重新执行它。请参见gh-7398
执行重复查询
要解决此问题,只需从await中删除第三个参数
NewSlotModel.updateOne
制作:

const a = await NewSlotModel.updateOne(
  { date: req.body.slotDate },
  { $set: update }
);
t98cgbkg

t98cgbkg2#

Mongoose v6。不再支持回调了。。检查图像。
const productCount =等待产品.计数文档((count)=〉计数)BAD
如果您有任何问题,请使用下面的方法。良好
enter image description here

相关问题