How to add element to mongoose object array in Nodejs


Mongoose array can set of objects basically a reference to other mongoose document placed in other document. Our task is to place a new element to MongoDB array of objects.

To add a new element we can use the $push command. In our Post example we had tags which need to added while updating the post.

Post.updateOne({_id:pst},
{
  $push:{'tags':ctag._id}
},
{  safe: true, upsert: true}
) 

$push will add the tag id to the tags object array

Alternatively we can afford the following method too. The difference is that the first one used inside a update command.

post.tags.push(stag)

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.