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

shayp
  • 44
  • 4
  • http://mongoosejs.com/docs/subdocs.html https://stackoverflow.com/questions/33049707/push-items-into-mongo-array-via-mongoose – Andrew Li Dec 13 '17 at 15:14

1 Answers1

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();
});
David Vicente
  • 3,091
  • 1
  • 17
  • 27