Search code examples
mongodbmongoosebody-parser

mongodb adding values to array field


Hey guys not giving an example since the question is pretty straightforward.

I have a mongodb schema in which I have a field called Teamnames which is an array so Teamnames: [String]

I am using body parser middleware to accept data from a form on my client side. There are about 10 different text boxes each having name as teamname1, teamname2, etc etc .

Whats the right syntax to update the mongodb field? I am doing findOneAndUpdate to retrieve the record from my collection after submitting the update and I wanted to update the Teamname array with the values. But I am kind of confused with the syntax and whats the right way to approach this. Can someone please help?


Solution

  • Try this:

     const value = await YourModel.findByIdAndUpdate(id, {
              $set: { teamnames: yourFormData }
             },
             {
              new: true,
              upsert: true,
            });