【发布时间】:2016-12-09 10:55:42
【问题描述】:
这是我的场景:
我有 2 个集合(表):项目和学生(关系是多对多的)。
我的模型是:
-
项目:
var ProjectSchema = new Schema({ name: { type: String }, description: { type: String }, user : { type : Mongoose.Schema.Types.ObjectId, ref : "User" } }); Mongoose.model('Project', ProjectSchema); -
用户:
var Userchema = new Schema({ name: { type: String }, surname: { type: String }, project : { type : Mongoose.Schema.Types.ObjectId, ref : "Project" } }); Mongoose.model('User', UserSchema);
在我看来,我有 2 个输入,其中接收项目的名称和描述,然后进行多选,为该项目选择 1 个或多个用户。当我点击确定时应该:
- 创建项目,并将所有在 BBDD 中选择为对象的用户添加到用户。
- 使用项目关联更新用户。
我尝试下一个,但只有在我选择 1 个用户时才起作用:
exports.addUserProject = function(req, res) {
var project=new svmp.Project();
project.name=req.body.name;
project.description=req.body.description;
project.user=req.body.user[0]._id;
project.save(function(err,project){
if (err) {
return res.send(400, {
message : getErrorMessage(err)
});
} else {
res.jsonp(project);
}
})
};
我的BBDD中的结果是下一个:
{ "_id" : ObjectId("57a200a38fae140913ac5413"), "user" : ObjectId("578f41ddb0641d961416c3f5"), "name" : "Project1", "Description" : "Project1 Desc","__v" : 0 }
感谢您的帮助
【问题讨论】:
标签: node.js mongodb mongoose mongoose-populate mongoose-schema