【问题标题】:mongoos - Exclude virtual schema fields with populatemongoose - 使用填充排除虚拟模式字段
【发布时间】:2018-10-22 05:24:51
【问题描述】:

我有一个项目架构,它有一个所有者属性,我曾经引用用户架构。现在我正在尝试填充所有者而不获取 userSchema 虚拟字段,这是我的架构。

用户架构

let userSchema = new mongoose.Schema({
 name: {type: String},
 email: {type: String},
 phoneNumber: {
   type: String,
   required: true,
   trim: true
 },
 devices: [String],
 verified: {
   phoneNumber: {
     type: Boolean,
     default: false
   }
 },
 settings: {
   showNumber: {type: Boolean},
   showEmail: {type: Boolean}
 },
 role: {
   type: String,
   enum: constants.user.roles,
   required: true,
   default: constants.user.defaultRole
 }
});

userSchema.virtual('isPhoneVerified').get(function () {
  return !!this.verified.phoneNumber;
});

module.exports = mongoose.model('user', userSchema);

项目架构

let itemSchema = new mongoose.Schema({
  title: {type: String, required: true},
  price: {type: Number},
  owner: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user',
    require: true
  }
});

let autoPopulate = function(next) {
   this.populate({
     path: 'owner',
    select: {name: 1, _id: 0, isPhoneVerified: 0}
   });
   next();
};

itemSchema.pre('find', autoPopulate);
itemSchema.pre('findOne', autoPopulate);

module.exports = mongoose.model('item', itemSchema);

所以当我尝试排除 isPhoneVerified 字段时出现此错误

MongoError: Projection cannot have a mix of inclusion and exclusion.

你能给我建议吗?

更新 我通过在toJson 中使用transform 属性找到了解决这种情况的方法。

userSchema.set('toJson', {
  virtuals: true,
  getters: true,
  transform: function (doc, ret) {
    delete ret._id;
    delete ret.isPhoneVerified;
    return ret;
  }
});

【问题讨论】:

    标签: mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    您不能排除虚拟字段,因为它没有任何意义,因为它与猫鼬有关。
    您可以执行以下操作:

    userSchema.set('toJSON', {
      virtuals: false
    });
    

    如果这是您的问题,则不会在响应中发送虚拟对象。

    【讨论】:

      【解决方案2】:

      如果您不想包含虚拟对象,则可以在不更改架构的情况下执行此操作。只需使用lean()。这是一种更简洁的方式,因为您不必编辑架构。

      Model.find(query)
        .lean()
        .populate('user', 'firstName lastName')
        .then(rec => {
          // do something
        })
        .catch(err => {
          // handle error
        })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-06
        • 2020-12-08
        • 2019-09-22
        • 2015-09-19
        • 2019-06-17
        • 2018-05-20
        • 1970-01-01
        • 2019-01-25
        相关资源
        最近更新 更多