1

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

akila arasan
  • 737
  • 3
  • 11
  • 26

2 Answers2

0

I think this is because your schema needs to define the enterprise_employee as an array. You have to explicitly tell Mongoose that it should be an 'Array' type.

Try this:

enterprise_employee: {
    type: Array,
    fields: [
        {
            employee_id: String,
            employee_name: String
        }
    ]
}
dyouberg
  • 2,206
  • 1
  • 11
  • 21
  • Error persists.Can you review me is this the right way of sending the details?{"enterprise_id" :2, "employee_id": 1 ,"employee_name" : "akila"} – akila arasan Sep 21 '16 at 13:30
  • In your case, the employee_id and enterprise_id are numbers not strings since there aren't quotes around them. Also you should try chridam's suggestion, it might be a cleaner way of doing what you're trying to do. – dyouberg Sep 21 '16 at 13:58
0

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
        }
    }
);
chridam
  • 100,957
  • 23
  • 236
  • 235