如何在 Node 中的 MongoDB 中使用 findOneAndUpdate

新手上路,请多包涵

说之前我已经将一个文档插入到一个 mongo 集合中。

     MongoClient.connect(url, function(err,db){
      if(err) {throw err;}
      else {
        document = {action: "alert",
                    protocol: "udp",
                    port: "80",
                    _id: "12" }
        var collection = db.collection("connections");
        collection.insertOne(document, function(err,result){
          if (err) {throw err;}
          else {
            console.log("Successful")
            db.close();
          }
        }
      }

现在我想更新协议字段。到目前为止我没有运气的是

     MongoClient.connect(url, function(err,db){
       if (err) { throw err; }
       else {
         var collection = db.collection("connections");
         collection.findOneAndUpdate({_id: "12"}, {$set: {protocol: "http"}}, {new: true}, function(err,doc) {
           if (err) { throw err; }
           else { console.log("Updated"); }
         });
       }
     });

我是否将错误的参数传递给 findOneAndUpdate 方法?我正确连接到数据库。

原文由 Spothedog1 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 525
1 个回答

我觉得你应该试试

MongoClient.connect(url, function(err,db){
   if (err) { throw err; }
   else {
     var collection = db.collection("connections");
     collection.findOneAndUpdate({_id: "12"}, {$set: {protocol: "http"}}, {upsert: true}, function(err,doc) {
       if (err) { throw err; }
       else { console.log("Updated"); }
     });
   }
 });

如果“upsert”设置为 true,则在没有文档匹配查询条件时创建一个新文档。

原文由 deleuterio 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题