【问题标题】:mongoose query .where/.and after .populate猫鼬查询 .where/.and 之后 .populate
【发布时间】:2016-02-21 22:59:57
【问题描述】:

我需要测试用户是否具有给定的 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 查询在这里什么都不做...

【问题讨论】:

  • 向我们展示您的查询...即使不工作的代码在这里也很有价值。
  • 在这种情况下,首先必须在角色集合中查询具有给定名称的角色,然后必须通过以下方式查询具有所述角色和项目的用户身份证。

标签: javascript node.js mongodb mongoose mongoose-populate


【解决方案1】:

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

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);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 2020-06-02
    • 2012-02-03
    • 2021-03-23
    • 2018-02-05
    相关资源
    最近更新 更多