繁体   English   中英

猫鼬查询.where /。和.populate之后

[英]mongoose query .where/.and after .populate

我需要测试用户是否具有给定的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
    }
});

我尝试填充然后在.where上应用,但是.where没有任何作用。
在填充后使用.and也不起作用。

如何在mongodb / mongoose中解决此问题?

谢谢!

// EDIT现在,我有类似的东西,它不起作用(.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查询在这里什么都不做...

现在,我只是在程序而不是数据库中进行比较。

User.findById(userId)
.populate('roles.role')
.exec(function(err, data){
    if(!err){
        if(data){
            if(data.roles.find(function(element, index, array){
                return element.project == projectId && element.role.name == roleName;
            }))
                return callback(true);
        }
    }
    return callback(false);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM