Search code examples
mongodbmongoosemongoose-schema

$push into Array in Object in the document Mongoose


How do I $push into the Array which is in the Object in the document in mongoose?

The schema looks like this

{
  rating: {
      usersRated: Array,
      rating: Number
  }
}

I have tried {rating: {$push: {usersRated: data.userId}}}, but it does not work.


Solution

  • You should update the collection.

    In your case:

    model.update({ _id: id }, { $push: { 'rating.usersRated': data.userId }}, callback);
    

    On update, you should pass the operator before the fields.