我需要测试用户是否具有给定的 id、具有指定 id 的项目和具有给定名称的角色。
var UserSchema = new Schema({
roles: [{
project: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Project',
},
role: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Role',
}
}]
});
和
var RoleSchema = new Schema({
name: {
type: String
}
});
我尝试 .populate 然后应用 .where,但 .where 什么也没做。
在填充后使用 .and 也不起作用。
如何在 mongodb/mongoose 中解决这个问题?
谢谢!
//编辑现在我有类似的东西,它不起作用(.where什么都不做)而且它真的不漂亮:
User.findById(userId)
.populate({
path: 'roles.role',
match: { 'name': roleName}
})
.where('roles.project').equals(projectId)
.exec(function(err, data){
data.roles = data.roles.filter(function(f){
return f.role;
})
if(!err){
if(data){
if(data.roles.length == 1) {
return true;
}
}
}
return false;
});
当我按照凯文 B 说的做时:
Role.findOne({name: roleName}, function(err, data){
if(!err){
if(data){
User.findById(userId)
.and([
{'roles.project': projectId},
{'roles.role': data._id}
])
.exec(function(err2, data2){
if(!err2){
if(data2){
console.log(data2);
}
}
});
}
}
});
.and 查询在这里什么都不做......