【发布时间】:2015-01-03 00:11:37
【问题描述】:
我有两个具有多对多关联的模型:用户、项目
换句话说:用户属于任意数量的项目,项目属于任意数量的用户。
现在我想检索属于某个用户 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;
}
}
};
【问题讨论】:
-
您应该发布模型定义的相关部分。