Home > front end >  insert id into type array mongodb
insert id into type array mongodb

Time:11-02

My mongodb collection login is structured as so:

email: "[email protected]"
password: "password"
full_name: "John Doe"
list_of_docs_bought: Array
   0: "g81h8"
   1: "fursr"

now, in my code, what I want to do is insert a new id into the list_of_docs_bought array. My code is as follows:

let collection = database.collection('login')
let doc = collection.updateOne({ email: req.session.username }, {$set: { list_of_docs_bought: '2xx729' }})

however, this isn't going to work because I need to essentially insert a new id into there, not update it. But if I use .insert(), I am not sure if that is going to work because it will insert a totally new record instead of just into the array. Can anyone offer some help?

CodePudding user response:

You can use upsert which does exactly what you need.

Explanation below is taken from the official docs.

  • Creates a new document if no documents match the filter. For more details see upsert behavior.
  • Updates a single document that matches the filter.

So you would need to change your code to that:

let doc = collection.updateOne({ email: req.session.username }, {$push: { list_of_docs_bought: '2xx729' }}, { upsert: true })

Edit: You need to use the $push operator in order to add an element in an array. The $set operator will just overwrite it.

  • Related