Search code examples
javascriptmongodbmongoosemongoose-schemanested-documents

Updating a schema within a schema Mongoose


Been trying to attempt to update a field within a nested array in my document.

Such as an example schema here..

childSchema = new Schema ( {
foo2 : String,
bar2 : String,
foobar : String
) };

Within this schema

parentSchema = new Schema ( {
foo1 : String,
bar1 : String,
nested : [childSchema]
)};

If I wanted to update bar2 (childSchema) based on foo2 matched string how would I go about this?

I have tried the following,

parentSchema.childSchema.updateOne( { 'nested.foo2' : 'string-that-matches' }, { $set: { 'nested.$.bar2' : 'new-string-for-bar2' } } )

I typically get the error

TypeError: Cannot read property 'updateOne' of undefined

I used to not have the childSchema like that, it was just made in the parentSchema. It was more for testing on separating them out.

I am sorry if I formatted this question wrong, and obviously I tried to do a mock schema set from my real thing. I figured that it's something more with my query than the set up.

Thanks!


Solution

  • parentSchema is enough to this update

    parentSchema.updateOne( { 'nested.foo2' : 'string-that-matches' }, { $set: { 'nested.$.bar2' : 'new-string-for-bar2' } } )