You cannot use $set and $push in the same update expression as nested statements.
The correct syntax for using update statements is:
{ <operator1>: { <field1>: <value1>, ... }, <operator2>: { <field2>: <value2>, ... }, ... }
where <operator1>, <operator2> can be from any of the update statements listed here .
To add a new element to an array, a single $push statement is enough, for example. you can use the findByIdAndUpdate update method to return the modified document as
Employeehierarchy.findByIdAndUpdate(employeeparent._id, { "$push": { "childrens": employee._id } }, { "new": true, "upsert": true }, function (err, managerparent) { if (err) throw err; console.log(managerparent); } );
Using the original update() syntax
Employeehierarchy.update( { "_id": employeeparent._id}, { "$push": { "childrens": employee._id } }, function (err, raw) { if (err) return handleError(err); console.log('The raw response from Mongo was ', raw); } );
in which the callback function takes arguments (err, raw) , where
err is an error if any eventsraw - full answer from Mongo
Since you want to check the changed document, I would suggest using the findByIdAndUpdate function, since the update() method will not give you the changed document, but just the full result of writing from mongo.
If you want to update the field in the document and add the element to the array at the same time, you can do
Employeehierarchy.findByIdAndUpdate(employeeparent._id, { "$set": { "name": "foo" }, "$push": { "childrens": employee._id } } { "new": true, "upsert": true }, function (err, managerparent) { if (err) throw err; console.log(managerparent); } );
The above will update the name field to "foo" and add the employee ID to the childrens array.