【问题标题】:Deselect ref field in Mongoose model取消选择猫鼬模型中的参考字段
【发布时间】:2020-04-07 12:11:54
【问题描述】:

在 Mongoose 中,如何确保默认情况下不返回字段 - 如果该字段使用 ref

const userSchema = new mongoose.Schema({

    // --- Works
    isActive: {
        type: Boolean,
        select: false,
    },

    // --- Does NOT work
    clientsList: [ {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Client',
        select: false,
    }],
});

如果我使用User.findById 检索此用户,则返回的用户对象将不包括isActive(如预期),但将包括clientsList(未预期)。

有没有办法取消选择第二个字段?

PS:我知道我可以在查询级别手动执行.select('-clientsList'),但更愿意取消选择它添加模型级别,类似于第一个字段。

【问题讨论】:

    标签: mongodb express mongoose mongoose-schema


    【解决方案1】:

    您需要排除数组本身,您目前正在排除数组内的值。

    要修复它,只需像这样更改您的 clientList 定义:

      clientsList: {
        type: [
          {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Client",
            select: false
          }
        ],
        select: false
      }
    

    【讨论】:

      【解决方案2】:

      您可以通过像这样声明clientsList 字段来解决问题:

      clientsList: {
        type: [ {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Salary'
        }],
        select: false,
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-15
        • 1970-01-01
        • 2015-01-14
        • 2013-01-25
        • 2015-03-16
        • 1970-01-01
        • 2013-10-07
        • 2022-12-10
        相关资源
        最近更新 更多