我有两个具有多对多关联的模型:用户、项目
换句话说:用户属于任意数量的项目,项目属于任意数量的用户。
现在我想检索属于某个用户id的所有项目。我如何才能做到这一点?
下面的查询返回我的数据库中的所有项目,其中包含一个users数组,当找到用户时,该数组有一个属性,否则为空。
Projects.find().populate('users',{id : my_user_id}); 项目模型
module.exports = {
attributes: {
name : {
type : 'string',
maxLength : 80,
required : true
},
users : {
collection : 'User',
via : 'projects'
},
}
}用户模型:
var User = {
// Enforce model schema in the case of schemaless databases
schema: true,
attributes: {
firstname : {
type: 'string',
size : 60
},
lastname : {
type: 'string',
size : 60
},
email : {
type: 'email',
unique: true,
required : true,
size : 80
},
passports : {
collection: 'Passport',
via: 'user'
},
projects : {
collection : 'Project',
via : 'users'
},
toJSON: function() {
var obj = this.toObject();
delete obj.passports;
delete obj.projects;
return obj;
}
}
};发布于 2014-11-07 08:44:37
你得走另一条路...也就是说,首先找到用户,然后像这样填充项目关联:
User.findOne(userid)
.populate('projects')
.exec(function(err, projects) {
// projects for that user returned
});发布于 2015-05-16 02:38:24
@Melvin的解决方案效果很好,但你也可以这样做:
Project.find({users: [my_user_id, second_user_id]})
.populate('users')
.exec(function(err, projects) {
});https://stackoverflow.com/questions/26780292
复制相似问题