'Mongoose push item to array if exists
I have a model schema like this :
favMovieSchema = mongoose.Schema({
movieId: {type: mongoose.SchemaTypes.ObjectId, ref: "Movie"},
rating: [{
type: Number,
// trim:true,
//MinMax validator
}],
});
movieSchema={
some fields,
favMovies: [favMovieSchema],
}
I want to push a rating into rating column if movieId already exists, to maintain a history of ratings done by a particular user. If it does not exists I am simply updating a new object with no issue.
I need some complex mongoose query to help me make a check for this.
Solution 1:[1]
It sounds like the complex query you need is:
collection.update({movieId: movieId}, {$push: {rating: rating}}, {upsert: true})
The first part is the matching: you are looking for a document with this movieId.
The 2nd part is the update: pushing one more rating to the rating array.
The 3rd part is the options, upsert meaning update if the matching exist and create a new document if it does not.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nimrod serok |
