I have a collection in mongodb called playlists, in which the following values are stored: userID and music, music is an Array which will contain a list of the songs that the user stores, however I have a problem when adding a song and it is that I can't find a way to do it, I thought that with findOneAndUpdate()
it would be achieved, but it only updates the existing value and what I want is for the new value to be added in such a way that the list grows.
async function update(user,music){
const playlist = await model.findOneAndUpdate({userID: user},{music:[music]})
await console.log(playlist)
console.log(user,music)
}
Model
const playlist = new Schema ({
userID: String,
music: Array,
})
Is there any way to add the data something equivalent to a merge()
Firebase?
I use the mongoose v 5.12.4 module
After searching I found that to add elements to an array it is done with the option
$push
, in the following way$push
it is used as an option when doing the document update operation, this causes the element to be added to the array, it can be declared in two ways in the model. You can also use$addToSet
this, it will add the value if it does not exist, but if it exists it will do nothing, that is, if music contains[cancion1,cancion2]
and you want to add song1 nothing will happen, but if you want to add song3 it will be added, its use is the same.Model
and it will work the same way. I hope to help someone.