Search code examples
javascriptmongodbmongoosemongoose-schemamongoose-populate

Creating many to many relationship in mongoose, populate is not a function


I'm trying to create a many to many relationship with mongoose for when I am creating an employee. However I'm getting the following error when I call the .post:

TypeError: Employee.create(...).populate is not a function

My .get in which I also use .populate isn't throwing any errors. Which makes me wonder why .post does. This is my code:

app.route('/api/employees')
    .get(function (req, res, next) {
        Employee.find()
          .populate('statuses')
          .exec(function (err, employee) {
            if (err) {
              return next(err);
            }

            res.json(employee);
        });
    })
    .post(function (req, res, next) {
        Employee.create(req.body)
        Employee.findById(req.params._id)
          .populate('statuses')
          .exec(function (err, employee) {
            if (err) {
              return next(err);
            }

          res.json(employee);
        });
    });

This is the status class:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var statusSchema = new Schema({
  name: ['In office', 'Project', 'Fired', 'Resigned', 'Ill']
});

module.exports = mongoose.model('Statuses', statusSchema);

And this is the employee class:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var employeeSchema = new Schema({
  name: String,
  division: ['IT','System','Trainee','Intern'],
  statuses: [{type:Schema.Types.ObjectId, ref: 'Statuses'}],
  project: Boolean,
  comment: {type:String, default:null}
});

module.exports = mongoose.model('Employees', employeeSchema);

It seems the .post also seems to throw a 500 error, but I'm not sure if the two are related. Is there an obvious error in above code or should I look for a mistake somewhere else?


Solution

  • The first thing you did wrong in the post request is that you never save the state, if the state saved then you save the status._id in the statuses.Then you do findById and find the employee._id and then you populate.

    Here is an example:

    Status.create(req.body, (err, status) => {
      if (err) console.error(`Error ${err}`)
    
      Employee.create({
        name: req.body.name,
        comment: req.body.comment,
        division: req.body.division,
        name: status._id
      }, (err, employee) => {
        if (err) console.error(`Error ${err}`)
    
        Employee
        .findById(employee._id)
        .populate('statuses')
        .exec((err, employee) => {
          if (err) console.error(`Error ${err}`)
    
          // console.log(JSON.stringify(employee))
          res.json(employee);
        })
      })
    })