node.js - mongoose findOneAndUpdate 返回两次,第一次为 null?

标签 node.js mongoose

这是我的代码:

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 时,是什么导致此代码返回两次?

最佳答案

试试这个:

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 })
  }
})

关于node.js - mongoose findOneAndUpdate 返回两次,第一次为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53536995/

相关文章:

node.js - 如何在 mongoose/mongodb 中使用不等于运算符?

node.js - 唯一和稀疏索引导致重复错误

node.js - 如何使用 mongoose 从父元素中删除 ObjectId?

node.js - 使用多对多关联对 Model.create 进行后续处理

javascript - 嵌入式 JS (ejs) 不会将数据渲染到浏览器

node.js - fromAuthHeaderAsBearerToken 在 NODE 中不起作用

javascript - 如何让文件继承node.js/express.js中的导出?

mysql - sequelize 多个外键只包含一列

javascript - 集合更改后 Mongoose 缓存中没有更新

javascript - MongooseJS 带有引用值的预保存钩子(Hook)