node.js 如何在 Node 中的 MongoDB 中使用 findOneAndUpdate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38078132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use findOneAndUpdate in MongoDB in Node
提问by Spothedog1
Say previously I had inserted a document into a mongo collection.
之前说我已将文档插入到 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();
}
}
}
Now I want to update the protocol field. What I have with no luck so far is
现在我想更新协议字段。到目前为止我没有运气的是
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"); }
});
}
});
Am I passing the wrong parameters to the findOneAndUpdate method? I connect to the database correctly.
我是否将错误的参数传递给了 findOneAndUpdate 方法?我正确连接到数据库。
回答by Douglas Eleuterio
I think you should try
我觉得你应该试试
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"); }
});
}
});
If "upsert" set to true, creates a new document when no document matches the query criteria.
如果“upsert”设置为true,则在没有文档与查询条件匹配时创建一个新文档。
回答by Relu Mesaros
your third {new: true}argument is not valid
你的第三个{new: true}论点无效
回答by udaykumar vangari
MongoClient.connect(url, function(err,db){
if (err) { throw err; }
else {
var collection = db.collection("connections");
collection.findOneAndUpdate({"_id": "12"}, {$set: {"protocol": "http"}}, function(err,doc) {
if (err) { throw err; }
else { console.log("Updated"); }
});
}
});
Here to update the record,it is not needed to use {upsert: true} and {new: true}. This solution works better.Try it once and suggest me if any errors in the code.
这里更新记录,不需要使用{upsert: true}和{new: true}。此解决方案效果更好。尝试一次,如果代码中有任何错误,请向我提出建议。
insert the update document if nothing matches the filter then use upsert.
如果没有与过滤器匹配的内容,则插入更新文档,然后使用 upsert。

