【问题标题】:Exclude field from a document based on another field value mongodb mongoose根据另一个字段值 mongodb mongoose 从文档中排除字段
【发布时间】:2021-11-13 08:17:38
【问题描述】:

我有一个users 架构,其中有一个companies 字段,如果role 字段值为admin,我只想选择它,否则它不应该在查找查询中返回。

user 架构:


const userInfoSchema = new mongoose.Schema({
  ...,
  companies: [
    {
      type: mongoose.Schema.ObjectId,
      ref: 'companyinfos',
    },
  ],
  role: {
    type: String,
    enum: ['user', 'admin', 'employee'],
    default: 'user',
  },
});

我试图通过使用 pre find hook 来解​​决这个问题,但无法排除公司字段。

userInfoSchema.post(/^find/, function (doc, next) {
  if (doc.role !== 'admin') {
    this.find({}).select('-companies');
  }

  next();
});

或者有没有什么方法可以根据role的值在userInfoSchema的companies字段中有条件地设置select

请帮忙。

【问题讨论】:

    标签: database mongodb mongoose mongoose-schema


    【解决方案1】:

    使用聚合

    db.collection.aggregate([
      {
        "$project": {
          companies: {
            "$cond": {
              "if": {
                $eq: [
                  "$role",
                  "admin"
                ]
              },
              "then": "$companies",
              "else": 0
            }
          }
        }
      },
      {
        $match: {
          companies: {
            $ne: 0
          }
        }
      }
    ])
    

    https://mongoplayground.net/p/I8HGvz6h7MP

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      • 2023-01-31
      • 2023-02-11
      • 2021-06-24
      • 2014-09-13
      • 2015-01-10
      相关资源
      最近更新 更多