I'm working with node and mongodb. I'm trying to grab a few records and then for each record contact an api get a result and create a new field and assign the result to it. I'm running into the error in the title, which occurring at the 'updateOne' line.
const collection = database.collection("test");
async function run() {
let records = [];
const cursor = collection.find(filter).limit(num);
await cursor.forEach(doc => records.push(doc));
while (records.length) {
const record = records.pop();
try {
.....
.....
collection.updateOne({ _id: record._id }, { $set: { "NewField": value}});
} catch (error) {
console.log('failed');
}
How can I fix this?
CodePudding user response:
Looking into your code I think you are just missing an await
on you updateOne()
function as:
while (records.length) {
const record = records.pop();
try {
.....
.....
await collection.updateOne({ _id: record._id }, { $set: { "NewField": value}});
} catch (error) {
console.log('failed');
}
Now, a couple of considerations:
If you are doing a lot of updates in a loop, you may consider doing it in Bulk:
https://www.mongodb.com/docs/manual/reference/method/Bulk.find.update/
for example:
const bulk = collection.initializeUnorderedBulkOp();
while (records.length) {
const record = records.pop();
...
bulk.find({ _id: record._id }).updateOne({ $set: { "NewField": value}});
}
await bulk.execute();
One other point you can reduce:
let records = [];
const cursor = collection.find(filter).limit(num);
await cursor.forEach(doc => records.push(doc));
to
let records = await collection.find(filter).limit(num).toArray()
I hope that helps you :)
CodePudding user response:
changing the line :
collection.updateOne({ _id: record._id }, { $set: { "NewField": value}});
to
await collection.updateOne({ _id: record._id }, { $set: { "NewField": value}})
should solve your problem.
Your code doesn't wait for the updateOne() to complete its execution and goes on to the client.close() statement which you propaby have it somewhere. So by the time it tries to update data to the db, the connection has already ended.