I have a very simple case. I want to update my collection every midnight. Im using node-schedule
:
schedule.scheduleJob('0 0 * * *', () => { Users.updateMany(); });
All I want to do, is to loop over every document in my collection (Users
) and then if User.created
is false
, I want to turn it into true
.
In javascript it would be:
for (let user in Users) { if (user.created === false) { user.created = true; } }
How to do it in mongoose? Thanks!
The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero.
Introduction to MongoDB updateMany() method The updateMany() method allows you to update all documents that satisfy a condition. The following shows the syntax of the updateMany() method: db.collection.updateMany(filter, update, options)
You can use updateMany()
methods of mongodb to update multiple document
Simple query is like this
db.collection.updateMany(filter, update, options)
For more doc of uppdateMany read here
As per your requirement the update code will be like this:
User.updateMany({"created": false}, {"$set":{"created": true}});
here you need to use $set because you just want to change created from true to false. For ref. If you want to change entire doc then you don't need to use $set
You first need a query to find the documents you want to update. This is simply:
{"created": false}
Then you need an update query to tell mongo how to update those documents:
{"$set":{"created": true}}
You need to use the $set
operator to specify which fields to change, otherwise it will overwrite the entire document. Finally you can combine these components into a single mongo call with an additional parameter to tell mongo we want to modify multiple documents:
User.update({"created": false}, {"$set":{"created": true}}, {"multi": true}, (err, writeResult) => {});
Mongoose tries to closely replicate the mongo API so all this information can be found solely within MongoDB's documentation: https://docs.mongodb.com/manual/reference/method/db.collection.update/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With