我是mongodb和Nodejs的新手,我想知道我的代码有什么问题,
我在使用updateOne时遇到更新操作文件必须包含原子操作符,
这是我的代码,
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://url-this-is-working";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbase = db.db("SampleNodeDB");
var myquery = { address: "Valley 345" };
var newvalues = { name: "Mickey", address: "Canyon 123" };
dbase.collection("customers").updateOne(myquery, newvalues, function(err, res) {
if (err) throw erre
console.log("1 document updated");
db.close();
});
});
Run Code Online (Sandbox Code Playgroud)
有人可以帮我识别和纠正问题,
谢谢!
小智 14
您尝试使用查询更新为新值
var newvalues = { name: "Mickey", address: "Canyon 123" };
Run Code Online (Sandbox Code Playgroud)
但你应该添加$set运算符,这是一个原子运算符,如$ inc,$ push等,以使其成为更新查询.像这样;
var newvalues = { $set: {name: "Mickey", address: "Canyon 123"} };
Run Code Online (Sandbox Code Playgroud)
updateOne() 方法具有以下形式。
db.collection.updateOne(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)
Run Code Online (Sandbox Code Playgroud)
例子
try {
db.restaurant.updateOne(
{ "name" : "Pizza Rat's Pizzaria" },
{ $set: {"_id" : 4, "violations" : 7, "borough" : "Manhattan" } },
{ upsert: true }
);
} catch (e) {
print(e);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7914 次 |
| 最近记录: |