Mongodb FindOne后跟updateOne,使用单个查询

Mongodb FindOne后跟updateOne,使用单个查询,mongodb,mongoose,mongodb-query,Mongodb,Mongoose,Mongodb Query,通过使用mongoDb驱动程序的“findOne”方法(无mongoose),我可以在以后使用检索到的文档进行更新吗 例如: document.collection('myCollection').findOne({ _id: myId }, (err, foundDoc) => { // **I need to do some multiple checks in between**, so I don't want to use "findOneAndUpdate()" //

通过使用mongoDb驱动程序的“findOne”方法(无mongoose),我可以在以后使用检索到的文档进行更新吗

例如:

document.collection('myCollection').findOne({ _id: myId }, (err, foundDoc) => {
  // **I need to do some multiple checks in between**, so I don't want to use "findOneAndUpdate()"
  // foundDoc is the retrieved document. Can I use it directly for update? (something like "foundDoc.update()")
  document.collection('myCollection').updateOne({ _id: myId }, { $set: { name: 'John' } });
});

如您所见,我基本上使用“updateOne”方法进行第二次查询(首先搜索文档,然后更新文档)。我是否可以避免这种情况,直接使用foundDoc进行更新?

如果要更新同一文档,不必调用
.findOne()
然后调用
.updateOne()
方法。默认情况下,
upsert
选项在
.upadateOne()
中设置为false,因此如果找不到文档,它将拒绝插入,否则将更新文档

 document.collection('myCollection').updateOne({ _id: myId }, { $set: { name: 'John' } });
.updateOne
在您的情况下应该足够了

另外,如果要添加一些筛选条件,
.updateOne()
支持如下所示:

db.collection.updateOne(
   <filter>,   // you can place filters here
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)
db.collection.updateOne(
,//您可以在此处放置过滤器
,
{
插入:,
writeConcern:,
排序规则:,
阵列过滤器:[,…]
}
)

链接:

我使用findOne是因为我想对文档进行一些检查(每个检查都可能触发不同的http响应),并且只有在这些检查之后,我才想更新文档。在这种情况下,如果可能的话,您可以使用带有
updateOne()
方法的过滤器。在答案中添加了更多细节。