猫鼬限制/允许文件

问题描述:

我有一个程序架构,看起来像这样:猫鼬限制/允许文件

var ProgramSchema = new Schema({ 
    active: { type: Boolean, default: false }, 
    name: { type: String, required: true }, 
    ... 
    user: { 
    ... 
    allowed: [{ 
     type: Schema.Types.ObjectId, 
     ref: 'User' 
    }], 
    restricted: [{ 
     type: Schema.Types.ObjectId, 
     ref: 'User' 
    }] 
    } 
}); 

如果允许不为空,并从登录的用户的User._id不是它,我不不想给他看文件。

如果受限制不是空的,并且来自登录用户的User._id在其中,我不想让他看到文档。

我的第一个想法是,当我通过Program.find()获取所有文档时,我循环遍历每个文档并检查文档是否应该返回。

但是没有比使用forEach更好的解决方案吗?就像使用猫鼬方法并在返回之前过滤文档一样?


解决方案

var query = { 
'active': true, //shows only active programs 
$or: [{ 'user.allowed': {$size: 0} }, { 'user.allowed': req.user._id }], //true if allowed is empty or has userId in it 
'user.restricted': { $ne: req.user._id } //true if restricted doesn't contain userId 
}; 

Program.find(query, 'name owner image categories user special', function (err, p) { 
    if(err) { return handleError(res, err); } 
}) 
.sort({_id: -1}) 
.exec(function(err, programs){ 
    if(err) { return handleError(res, err); } 
    res.json(200, programs); 
}); 

为什么user.allowed数组中没有查询your_user_id

db.programs.find({'user.allowed': 'your_user_id'});