1

I am new to Mongoose and MongoDB, and I'm trying to update the values of the following model :

var userSchema = mongoose.Schema({
  username  : String,
  playlist  : [{
    name    : String,
    active  : {type: Boolean, default: false},
  }]
});

What I want to do is to set all the playlists of one user to false, then set only one to true. And by doing the following request, it happens to erase the informations in my playlists :

this.model('User').findByIdAndUpdate(userId, {$set:{playlist:{active:false}}})
  .exec(
    function(err, user){
      //DO callback treatment here
    });

I have seen some people saying that once they retrieved the User, they had to do a foreach on the subarray, but is there no way to use directly mongoose and mongodb to do such a treatment ?

Thanks for your answer !

2 Answers 2

2

If you do:

{$set:{playlist:{active:false}}}

Then you're replacing the whole playlist array as you $set the playlist argument. You should be able to do the following to just add an extra field to playlist:

{$set:{"playlist.active": false}}

Here you're not modifying the playlist argument, but instead just instruct MongoDB to do something with the active field in playlist.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

{$set: {'playlist.$.active': false}

Read about it here

1 Comment

Thanks, it did the trick ! I had to specify the playlist to update and then specifying the field with the positionnal operator it worked : this.model('User').update({_id:userId, 'playlist.active':true},{$set:{"playlist.$.active":false}}) .exec( function(err, user){ //CODE MANAGEMENT HERE });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.