I have an array of objects
df =[{user: "name1", newdata: "data1"},
{user: "name2", newdata: "data3"},
....
]
I have a collection with user and key1 fields. I want to find the users and update 'key1' with dato.newdata. I tried to include in a for loop, but it does not work. This is my code:
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));
}
}
);
}
})
Additional information: I noticed that it works for the first user found. Maybe updateOne returns a promise and I don't manage it correctly?
I have tried this other code as suggested by some of you. But it does not work.:
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);
}
})
The compiler says: SyntaxError: await is only valid in async function
{ $set: { newdata: dato.newdata } }instead of{ $set: { key1: dato.newdata } }, if you want to updatenewdatafield.key1field withdato.newdata. I have updated my question to avoid confussions.