Search code examples
mongodbmongoosesubdocument

Trouble in inserting sub-documents using mongoose


I created an Enterprise database using mongoose in node-express project.Now I need to add employee sub document in the enterprise_employee field of the enterprise database, but it throws an error. Following code snippet is my schema

var mongoose= require('mongoose');

var Enterprise= new mongoose.Schema({
     enterprise_id:{
		type:String
	},
	enterprise_name:{
		type:String
	},
	enterprise_email:{
		type:String
	},
	enterprise_employee: [{employee_id:Number, employee_name:String}]
});


module.exports={
	Enterprise:Enterprise
};

This code snippet is the route for adding employee sub-document

var mongoose = require('mongoose');

var Enterprise = mongoose.model('Enterprise_gpy');

var addEmployee = function(req, res){

	Enterprise.findOne({"enterprise_id":req.body.enterprise_id},function(err, res){
		if(err){
			console.log('NO SUCH ORGANISATION');
			res.json(err);
		} else {
			Enterprise.enterprise_employee.push({
				"employee_id": req.body.employee_id,
				"employee_name":req.body.employee_name
			});
		}
	});
}
module.exports={
	addEmployee:addEmployee
};

This the error thrown

throw er; // Unhandled 'error' event ^ TypeError: Cannot read property 'push' of undefined


Solution

  • Seems like what you need is an update operation that uses the $push operator to add the elements to the array field. The following example demonstrates this:

    Enterprise.findOneAndUpdate(
        { "enterprise_id": req.body.enterprise_id },
        {
            "$push": {
                "enterprise_employee": {
                    "employee_id": req.body.employee_id,
                    "employee_name":req.body.employee_name
                }
            }
        },
        { "new": true }, // return the modified document
        function(err, enterprise) {
            if (err) {
                console.log('NO SUCH ORGANISATION');
                res.json(err);
            } else {
                console.log(enterprise); // modified document
            }
        }
    );