John doe
John doe

Reputation: 3870

How to update a value in a mongoose document?

I am trying to modify a piece of code written by another person.

I need to update a mongodb document rather than removing it.

Here is the code :

const docs = await docsModel.find({});

for (const doc of docs) {
  doc.remove();
}

I need to update rather than remove. I've tried this :

const docs = await docsModel.find({});

for (const doc of docs) {
  doc.updateOne({field_I_want_to_update : "new_value"});
}

But it doesn't work.

Any suggestion ?

Upvotes: 1

Views: 60

Answers (2)

user14520680
user14520680

Reputation:

You can use mongoose updateMany function which takes in a filter and an object of keys and values to update. wrap the object in a $set property. In theory, you could for-loop and use findByIdAndUpdate but that's a resource hog. So something like

await docsModel.updateMany({}, {$set: { /*insert field name*/: /*insert field value*/ } });

Upvotes: 1

Gynteniuxas
Gynteniuxas

Reputation: 7093

Depends on situation.

If you want to update multiple document with the same value, then better would be:

doc.updateMany(<filter>, { $set: { field_I_want_to_update : "new_value" } });

Where: <filter> would be something like: { _id: <validId> } or { _id: { $in: [<array_of_ids>] } }


If you want to update multiple documents with dynamic values, then this would work:

const docs = await docsModel.find({});

docs.forEach(function(doc) {
  await docsModel.updateOne({ _id: doc._id }, { $set: { field_I_want_to_update: "new_dynamic_value" } });
});

Comparing to your case, you're missing <filter> as the first parameter, and in second you need to start with $set: { <field>: <value> } rather with { <field>: <value> }

Upvotes: 1

Related Questions