Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB adding ObjectId to array of IDs

enter image description hereI have Poems schema which has a linked array of ObjectIds under field name ‘communities’:

    { _id: ObjectId("61659ef70e87b90018f7baa1"),
  schemaName: 'Poem',
  helps: [ ObjectId("5d15c609832d390c41ab6872") ],
  communities: 
   [ ObjectId("5eafbabaf0be6f0017303eb3"),
     ObjectId("5eba549a45bd9300170f6311") ],

I am trying to add a new ObjectId to the array using updateOne and $push:

    db.poems.updateOne(
  {title: "My stillness"},
  {$push: {communities: {ObjectId: ('61f942b737bdc10018722539')}}}
  )

While the new Id gets added, it is not in the correct format (see also attached image from MongoDB Compass for further clarity on the difference in format). How can I adjust my updateOne/$push method to add the ObjectId in the correct format? Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    { _id: ObjectId("61659ef70e87b90018f7baa1"),
  schemaName: 'Poem',
  helps: [ ObjectId("5d15c609832d390c41ab6872") ],
  communities: 
   [ ObjectId("5eafbabaf0be6f0017303eb3"),
     ObjectId("5eba549a45bd9300170f6311"),
     { ObjectId: '61f942b737bdc10018722539' } ],

>Solution :

You are pushing key-value pair into the array.

ObjectId: ('61f942b737bdc10018722539')

Instead, it should be:

ObjectId('61f942b737bdc10018722539')
db.poems.updateOne(
  { title: "My stillness" },
  { $push: { communities: ObjectId('61f942b737bdc10018722539') } }
)

Sample Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading