QA:mongoose中设置virtual后不工作问题

virtual提供了更方便的一些扩展属性或者关联数据api,但是当我在设置后发现不工作,原来代码如下

const _schema = new Schema({
  creator: { type: Schema.Types.ObjectId, ref: 'Users' },
  title: { type: String, default: '' },
  file: { type: String },
  remark: { type: String, default: '' },
  updateAt: { type: Date, default: Date.now },
  createAt: { type: Date, default: Date.now },
  count: { type: Number, default: 0 },
  enable: { type: Boolean, default: true },
  //状态
  status: {
    type: Number,
    required: true,
    default: 0,
  },
});


_schema.virtual('counter', {
  ref: 'xxx',
  localField: '_id', // Find people where `localField`
  foreignField: 'group', // is equal to `foreignField`
  count: true, // And only get the number of docs
});

issue关联:https://stackoverflow.com/questions/48421489/mongoose-virtual-not-working

解决方案,需要在2个序列化方法中开启支持

_schema.set('toObject', { virtuals: true });
_schema.set('toJSON', { virtuals: true });

注意

开启后,如果是普通属性拼接没有性能问题,如果是外键关联,注意序列化产生的一系列性能问题,合理使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值