Jua*_*uan 5 arrays mongodb node.js
我有一个对象数组
df =[{user: "name1", newdata: "data1"},
{user: "name2", newdata: "data3"},
....
]
Run Code Online (Sandbox Code Playgroud)
我有一个包含user
和key1
字段的集合。我想找到用户并使用 更新“key1” dato.newdata
。我尝试将其包含在 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));
}
}
);
}
})
Run Code Online (Sandbox Code Playgroud)
附加信息:我注意到它适用于找到的第一个用户。也许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);
}
})
Run Code Online (Sandbox Code Playgroud)
编译器说:SyntaxError: await is only valid in async function
gpr*_*our -1
MongoDB 调用是异步的,但截至目前,循环已完成所有迭代,并且不会等待操作结束。
我认为你可以做这样的事情
async changeValue(user, newData) {
client.db(dbasename).collection(collectionname).updateOne(
{user: user},
{$set: {key1: newdata}},
function(error,result){
if (error) console.log(error);
if (result) {
console.log(JSON.stringify(result));
}
}
);
}
for (dato of df){
await changeValue(dato.user, dato.newdata);
}
Run Code Online (Sandbox Code Playgroud)
这只是一个粗略的想法,您可能需要为此做一些更改。但我认为这可能有助于理解需要做什么。