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 });
注意
开启后,如果是普通属性拼接没有性能问题,如果是外键关联,注意序列化产生的一系列性能问题,合理使用。