在 Mongoose 模型中取消选择 ref 字段

Deselect ref field in Mongoose model

在 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'),但更愿意取消选择它添加模型级别,类似于第一个字段。

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

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

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

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

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