Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何避免在mongoose中多次找到同一文档?_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js 如何避免在mongoose中多次找到同一文档?

Node.js 如何避免在mongoose中多次找到同一文档?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我是猫鼬的新手,所以如果这听起来很愚蠢,请原谅我 对于每次编辑,我都希望存储历史值并修改集合的现有值。 这是代码 collection.findById(type_id).select({ "history": 0 }) .then(function(data){ var changes = { data : data, by : user_id } return collection.findOneAndUpdateAsync({_id:type_id},

我是猫鼬的新手,所以如果这听起来很愚蠢,请原谅我

对于每次编辑,我都希望存储历史值并修改集合的现有值。 这是代码

 collection.findById(type_id).select({ "history": 0 })


 .then(function(data){

   var changes =  { data : data, by : user_id }
  return  collection.findOneAndUpdateAsync({_id:type_id}, 
            {$push: {"history": changes }}) 
     })


  .then(function(data){
 return  collection.findOneAndUpdateAsync({_id:type_id}, info) 
})


   .then(function(res){

  resolve(res) })
这段代码工作得很好,但我不想对同一个集合进行多次查找。 如果你能提出更好、更有效的建议,那就太好了


提前感谢。:)

我认为在原子更新中不可能做到所有这一切。您所能做的最好是将对服务器的调用次数减少到两次:您的第一次调用是使用更新,并且
new
选项设置为false(默认),这将允许您访问 更新之前的数据。然后,您可以使用第二个调用使用此数据更新历史记录。例如:

collection.findByIdAndUpdateAsync(type_id, info /*, { "new": false } */)
     .then(function(data){
        var changes =  { 
            "data": data, 
            "by": user_id 
        };
        return  collection.findByIdAndUpdateAsync(
            type_id, 
            { "$push": { "history": changes } },
            { "new": true }
        ); 
    })
    .then(function(res){  resolve(res) });