Node.js findOneAndUpdate在插入时返回null?

Node.js findOneAndUpdate在插入时返回null?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我想要的是: 如果插入成功,即使文档以前不存在,也返回1 如果更新成功,则返回1 但我似乎无法通过findOneAndUpdate实现这一点,它只在文档存在并成功更新时返回结果 我的问题是: User.findOneAndUpdate( { email: email }, { $set: { verified: 1 } }, { upsert: true } ).exec(callback); 假设希望结果是更新后的文档,则需要修改查询,使其如下所示: User.findOneAn

我想要的是:

  • 如果插入成功,即使文档以前不存在,也返回
    1
  • 如果更新成功,则返回
    1
  • 但我似乎无法通过
    findOneAndUpdate
    实现这一点,它只在文档存在并成功更新时返回结果

    我的问题是:

    User.findOneAndUpdate(
      { email: email },
      { $set: { verified: 1 } },
      { upsert: true }
    ).exec(callback);
    

    假设希望结果是更新后的文档,则需要修改查询,使其如下所示:

    User.findOneAndUpdate(
      { email: email },
      { $set: { verified: 1 } },
      { upsert: true, returnNewDocument: true }
    ).exec(callback);
    

    returnNewDocument
    属性将使回调返回更新的文档,而不是原始文档。如果在不存在的文档上进行upsert,它将返回新文档而不是空集。

    您可以访问本机驱动程序来调用基础集合的方法,该方法将在回调中从Mongo返回完整响应,作为您可以使用的对象。比如说

    User.collection.updateOne(
        { "email": email },
        { "$set": { "verified": 1 } },
        { "upsert": true },
        function(err, result) {
    
            // The number of documents that matched the filter.
            console.log(result.matchedCount); 
    
            // The number of documents that were modified.    
            console.log(result.modifiedCount);  
    
            // The number of documents upserted.  
            console.log(result.upsertedCount);   
    
            // The total count of documents scanned. 
            console.log(result.result.n);     
    
            // The total count of documents modified.
            console.log(result.result.nModified); 
        }
    );
    
    在这种情况下,您很可能需要检查
    result.result.nModified
    result.upsertedCount
    属性以进行上述调用。

    查看文档。