I am facing an issue while trying to establish a many-to-many relationship using mongoose for employee creation. When I call the .post
method, I encounter the following error:
TypeError: Employee.create(...).populate is not a function
Interestingly, my .get
method which also utilizes .populate
runs without any errors. This discrepancy has me puzzled about why the .post
method is throwing an error. Here is the relevant code snippet:
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);
});
});
Below is the definition of 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 how the employee class is defined:
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);
The .post
method seems to be causing a 500 error as well, leading me to wonder if there might be some connection between the two issues. Can you spot any obvious error in the above code, or should I investigate elsewhere for potential mistakes?