1

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' } ],
}

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the very quick reply, yes that's what I need, i knew it would be something simple! Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.