【发布时间】:2020-03-17 16:45:25
【问题描述】:
我有一个对象数组
df =[{user: "name1", newdata: "data1"},
{user: "name2", newdata: "data3"},
....
]
我有一个包含 user 和 key1 字段的集合。我想找到用户并用dato.newdata 更新'key1'。我试图包含在一个 for 循环中,但它不起作用。这是我的代码:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
client.connect(function(error){
for (dato of df){
client.db(dbasename).collection(collectionname).updateOne(
{user: dato.user},
{$set: {key1: dato.newdata}},
function(error,result){
if (error) console.log(error);
if (result) {
console.log(JSON.stringify(result));
}
}
);
}
})
附加信息:我注意到它适用于找到的第一个用户。也许updateOne 返回了一个承诺,而我没有正确管理它?
我已经按照你们中的一些人的建议尝试了其他代码。但它不起作用。:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
async function changeValue (dbasename,collectionname, user, newData) {
client.db(dbasename).collection(collectionname).updateOne(
{user: user},
{$set: {key1: newdata}},
{upsert:false},
{multi:false},
function(error,result){
if (error) console.log(error);
if (result) {
console.log(JSON.stringify(result));
}
}
);
}
client.connect(function(error){
for (dato of df){
await changeValue(dbasename,collectionname, dato.user, dato.newdata);
}
})
编译器说:SyntaxError: await is only valid in async function
【问题讨论】:
-
我想
{ $set: { newdata: dato.newdata } }而不是{ $set: { key1: dato.newdata } },如果你想更新newdata字段。 -
不,我想用
dato.newdata更新key1字段。我已经更新了我的问题以避免混淆。