0

I'm using node.js and mongoose in my app. I have one Schema and a sub-schema.

const childrenSchema = new mongoose.Schema({
  name: { type: String, required: true, trim: true },
  hobbies: [String]
})

const parentSchema  = new mongoose.Schema({
  name: {
   type: String, trim: true, required: true,
  },
  children: [childrenSchema],
})

const parent = mongoose.model('parent', parentSchema)

I want to change a specific child inside a parrent. I've tried something like this:

const parentId = '1234'

const childToUpdate = {
  _id: '8765432',
  hobbies: ['guitar', 'javascript']
}

Parent.findOneAndUpdate({ _id: parentId}, { $set: { children: { 
 childToUpdate } } },
{ fields: { children: 1 }, new: true
})

Thanks for everyone's help

1

1 Answer 1

0

As you are using Mongoose, if you want to add a new children, you can take advantage of mongoose features

Parent.findOne({ _id: parentId}).exec()
.then(parent => {
   return parent.children.push(childToUpdate).save();
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.