mongoos - 使用populate排除虚拟架构字段

时间:2018-05-11 18:36:43

标签: mongoose mongoose-schema mongoose-populate

我有一个Item架构,它有一个我用来引用用户架构的所有者属性..现在我正在尝试填充所有者而不获取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.

你能建议我吗?

更新 我在transform中使用toJson属性找到了此案例的解决方案。

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

2 个答案:

答案 0 :(得分:0)

您不能排除虚拟字段,因为它没有任何意义,因为它与猫鼬有关 你能做的是以下几点:

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

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

答案 1 :(得分:0)

如果您不想包括虚拟机,则可以在不更改架构的情况下进行。只需使用package main import ( "bytes" "fmt" ) func main() { var b bytes.Buffer b.WriteString("W") b.WriteString("o") b.WriteString("r") b.WriteString("l") b.WriteString("d") var a bytes.Buffer a.WriteString("Hello ") a.WriteString(b.String()) fmt.Println(a.String()) } 。这是一种更简洁的方法,因为您不必编辑架构。

lean()
相关问题