【问题标题】:MongooseError: Query was already executed:MongooseError:查询已执行:
【发布时间】:2022-01-10 15:00:43
【问题描述】:

我正在尝试更新文档,但错误提示已执行查询。

MongooseError:查询已执行: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' });
  }
});

我哪里错了?

【问题讨论】:

    标签: javascript mongodb express mongoose mongodb-query


    【解决方案1】:

    您在代码中同时使用 async/await 和回调,导致 mongoose 抛出错误。 使用它们的实际效果正是您收到的错误类型:

    查询已执行

    Mongoose v6 不允许重复查询。

    Mongoose 不再允许执行相同的查询对象两次。如果 你这样做,你会得到一个查询已执行错误。执行 两次相同的查询实例通常表示混合回调 和承诺,但如果您需要执行两次相同的查询,您可以 调用 Query#clone() 来克隆查询并重新执行它。见 gh-7398

    Duplicate Query Execution

    要解决这个问题,只需从 await 中删除第三个参数

    NewSlotModel.updateOne

    制作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 2011-02-26
      • 2023-03-07
      相关资源
      最近更新 更多