Mongoose / mongodb - 原子查找

Mongoose / mongodb - Atomic find

这更像是 "hey is this the way mongoose / mongodb works" 而不是我该怎么做?

让我具体说明一下:

Model.find({name:'jim'}, function(err, jim){
    // i should happen first & find 0 jim's 
    new Model({name:'jim'}).save( ... );
});

Model.find({name:'jim'}, function(err, jim){
    // i should happen second & find 1 jim 
    new Model({name:'jim'}).save( ... );
});

我希望找到的所有内容都包含在该模型中,以便在保存新模型之前插入该模型。有什么想法吗?

the mongoose documentation

很好地涵盖了这一点

更像是:

Model.findOne({name:"jim"}, function(err, jim) {
  if (err) return handleError(err);

  jim.newField = "new value";
  jim.save(function (err) {
    if (err) return handleError(err);
    res.send(jim);
  });
});

它不会是原子的,因为您会找到 'jim' 然后在执行回调函数期间,'jim' 文档可能会因某些不同的客户端操作而改变。

我链接到的文档提供了其他更新原子文档的方法。

答案来自评论中的引用:

... data.locked = true;
Model.findOneAndUpdate(query, data, {upsert:true}, function(err, doc){...} );
// in your callback function - you can query against models w/ that 
// locked attribute being true 
//- if your logic is true keep&update record , else **remove**