【问题标题】:Mongoose restricted/allowed documentsMongoose 限制/允许的文件
【发布时间】:2014-09-30 15:30:23
【问题描述】:

我有一个如下所示的程序架构:

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

如果 allowed 不为空且已登录用户的 User._id 不在其中,我不想向他显示该文档。

如果 restricted 不为空,并且已登录用户的 User._id 在其中,我也不想向他展示该文档。

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

但是没有比使用 forEach 更好的解决方案吗?喜欢在返回之前使用 mongoose 方法和过滤文档?


解决方案

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

【问题讨论】:

    标签: node.js mongoose underscore.js lodash


    【解决方案1】:

    为什么不在user.allowed 数组中查询your_user_id

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      • 2010-12-23
      • 1970-01-01
      相关资源
      最近更新 更多