Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 507 Vote(s) - 3.48 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Update many in mongoose

#1
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!


### **Edit**: The story is very simple, I just want to iterate over every element in my db using mongoose and if iterated element has field "created" === false, change it to true.
Reply

#2
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:

[To see links please register here]

Reply

#3
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][1]

As per your **requirement** the update **code** will be like this:

User.updateMany({"created": false}, {"$set":{"created": true}});

here you need to use [$set][2] 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**


[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through