【问题标题】:mongoose findOneAndUpdate returns twice with null on first?mongoose findOneAndUpdate 返回两次,第一次返回 null?
【发布时间】:2019-05-01 09:31:22
【问题描述】:

这是我的代码:

router.post('/update_todo', async (req, res) => {
  const { todoId, userId, complete } = req.body;
  try {
    const todo = await Todo.findOneAndUpdate(
      { _id: todoId, userId },
      { $set: { complete: !complete } },
      { new: true } // return latest
    ).populate('userId', '_id');
    console.log('todo pdated', todo)
    res.json({ todo })
  } catch (error) {
    res.status(400).json({ error })
  }
})

当我尝试登录时,它会返回两次?

todo pdated null
todo pdated { complete: true,
_id: 5c003223ec8c1350b8c77b4f,
text: 'wearasdasd asd 2222',
userId: { _id: 5bf3b0b676bcc8176422e94e },
createdAt: 2018-11-29T18:38:27.156Z,
updatedAt: 2018-11-29T23:31:57.022Z,
__v: 0 }

当我使用 async/await 时,是什么导致此代码返回两次?

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    我有一个猜测,虽然您的问题缺乏足够的数据来确定:我认为这是 async/await 的问题,但您的代码运行了两次,因为浏览器发出 Preflight OPTION 请求:

    ...“预检”请求首先通过 OPTIONS 发送 HTTP 请求 方法到另一个域上的资源,以确定 实际请求是否可以安全发送。

    为了防止这种情况,我建议在 CORS 场景中使用这段代码,在系统到达您的业务逻辑之前返回 OPTIONS 请求:

    app.use(function (req, res, next) {
      res.header("Access-Control-Allow-Origin", '*');
      ...
      if (req.method === 'OPTIONS') {
        res.sendStatus(200);
      }
      else {
        next();
      }
    });
    

    【讨论】:

      【解决方案2】:

      试试这个:

      router.post('/update_todo', async (req, res) => {
        const { todoId, userId, complete } = req.body;
        try {
      
            Todo.findOneAndUpdate({_id: todoId,userId:userId},{$set:{complete: !complete}}, {new: true}, (err, doc) => {
              if (err) {
              console.log("Something wrong when updating data!");
              }
              console.log('todo updated', doc)
              res.json({ doc })
           });
      
      } catch (error) {
          res.status(400).json({ error })
        }
      })
      

      【讨论】:

        猜你喜欢
        • 2016-01-26
        • 1970-01-01
        • 1970-01-01
        • 2019-10-14
        • 2020-06-21
        • 1970-01-01
        • 1970-01-01
        • 2018-12-24
        • 1970-01-01
        相关资源
        最近更新 更多