0

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' } ],
}
Yong Shun
  • 35,286
  • 4
  • 24
  • 46
PYP
  • 125
  • 13

1 Answers1

3

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

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • Thanks for the very quick reply, yes that's what I need, i knew it would be something simple! Thanks a lot! – PYP Jun 28 '22 at 00:48