[英]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
:但是,当我调用.post
时出现以下错误:
TypeError: Employee.create(...).populate is not a function
My .get
in which I also use .populate
isn't throwing any errors.我也在其中使用.populate
.get
没有抛出任何错误。 Which makes me wonder why .post
does.这让我想知道为什么.post
会。 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.似乎.post
似乎也抛出了 500 错误,但我不确定两者是否相关。 Is there an obvious error in above code or should I look for a mistake somewhere else?上面的代码是否有明显的错误,还是我应该在其他地方寻找错误?
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.你在 post 请求中做错的第一件事是你从不保存状态,如果状态保存,那么你将 status._id 保存在状态中。然后你做 findById 并找到 employee._id 然后你填充。
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);
})
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.