Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update same field of all documents in collection in mongoose [duplicate]

i have this collection (not exactly what I have, just for example). I want to update all "numberOfViewsPerWeek" field into 0 just like reset.

{
    "_id" : ObjectId("594d2359bf170b0828690bf7"),
    "owner" : ObjectId("594c126285f0922a985083c1"),
    "numberOfViewsSincePost" : 15,
    "numberOfViewsPerWeek" : 4,
}

{
    "_id" : ObjectId("594d709addb8691cf067fa73"),
    "owner" : ObjectId("594c126285f0922a985083c1"),
    "numberOfViewsSincePost" : 10,
    "numberOfViewsPerWeek" : 2,
}

{
    "_id" : ObjectId("764d709addb8691cf067fa70"),
    "owner" : ObjectId("594c126285f0922a985083c1"),
    "numberOfViewsSincePost" : 12,
    "numberOfViewsPerWeek" : 7,
}
...

I'd try to use update but it only update the first document, my code is this

Property.update({}, {'$set': {'numberOfViewsPerWeek' : 0}}, function(error, properties){

        if(error){
            console.log(error);
        }

        if(!properties){
            console.log('Something went wrong');
        }

        console.log('success update view');
    });

what should I do? thanks in advance

like image 204
JerVi Avatar asked Jan 04 '23 20:01

JerVi


1 Answers

I actually think a lot of people have problems with this.
You should include an option called multi: true.

Ex:

Property.update({}, {'$set': {'numberOfViewsPerWeek' : 0}}, {multi: true},
   function(error, properties){/* ... rest of the code*/

Docs:

By default, the update() method updates a single document. Set the Multi Parameter to update all documents that match the query criteria.

I don't know why they did this, I find it unintuitive.
In my opinion updating all documents should be the default.

Update for mongo >= 3.2: To resolve the confusion prefer using .updateOne or .updateMany which sets the multi flag automatically.

like image 106
Omri Luzon Avatar answered Jan 06 '23 11:01

Omri Luzon