Search code examples
node.jsmongodbmongoosemongodb-querymongodb-update

MongoDB adding ObjectId to array of IDs


enter image description here

I 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

{ 
    _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