【问题标题】:How to update 2 collections with one request in mongoDB?如何在 mongoDB 中用一个请求更新 2 个集合?
【发布时间】:2021-04-13 15:37:14
【问题描述】:

我有以下使用 express 和 mongoose 的路线,从一条路线更新 2 个集合。更新工作并反映在 MongoDb 中,但是,在请求结束时服务器崩溃并出现错误:代码:'ERR_HTTP_HEADERS_SENT'。有没有办法让我避免这个错误?

router.post("/user-adopted", verify, (req, res) => {
  const userId = req.body.userId;
  const petId = req.body.petId;

    User.findOneAndUpdate(
      { _id: userId },
      { adoptedPet: petId, petId: false, adoptionRequest: false },
      function (err, result) {
          if..else..
      }
    );

  Data.findOneAndUpdate(
    { _id: petId },
    { adopted: true },
    function (err, result) {
     if...else..
  );
});

【问题讨论】:

    标签: node.js mongodb express mongoose axios


    【解决方案1】:

    一旦更新用户记录,它就会执行您在回调中定义的操作,并且数据记录被忽略,因此为了防止在用户的回调中更新数据记录并尝试使用 updateOne() findOneAndUpdate() 的:

    User.updateOne(
      { _id: userId },
      { adoptedPet: petId, petId: false, adoptionRequest: false },
      function (err, result) {
        if(err) res.send(err)
        Data.updateOne(
          { _id: petId },
          { adopted: true },
          function (err, result) {
            if(err)
            res.send(err)
            else{
              // Redirect where you want to  go
            }
          }
        );
      }
    );
    
    

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 2012-10-07
      相关资源
      最近更新 更多