mongo db findOneAndUpdate不返回文档而是对其进行更新

时间:2019-09-13 18:00:31

标签: mongodb

findOneAndUpdate更新文档,但返回错误

collection.findOneAndUpdate(
    { verificationHash: req.query.hash },
    { $unset: {verificationHash: ''}}).then((err, user) => {//some code}
);

在这种情况下,我的文档已更新,但回调中的用户始终未定义,错误内容看起来像

{
   lastErrorObject: {n:1, updatedExisting: true},
   value: document,
   ok: 1
}

我在这里丢失了什么吗,还是这是返回回调中对象的方式?

1 个答案:

答案 0 :(得分:0)

When executing .findOneAndUpdate in mongoDB then use {returnNewDocument: true} or if using mongoose you can use {new : true}

Set the returnNewDocument as true and you will get updated document.
 collection.findOneAndUpdate(
 { verificationHash: req.query.hash }, // query
 { $unset: {verificationHash: ''}},  // update condition
 { returnNewDocument: true }, // returns updated document
  function (err, documents) {
        res.send({ error: err, affected: documents });
        db.close();
    }
 )