簡體   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