2020年
您可以通过在模型中添加以下对象字段来设置虚拟对象。
toJSON: { virtuals: true },
toObject: { virtuals: true }
上面的例子和下面的例子是等价的,但上面的例子很简短。
itemSchema.set('toJSON', {
virtuals: true
});
这是示例
模型
const itemsSchema = new mongoose.Schema({
image: {
type: String,
trim: true,
required: [true, 'Please provide item image']
},
color: {
type: String,
trim: true
},
size: {
type: String,
trim: true
},
price: {
type: Number,
required: [true, 'Please provide item price']
},
shipping: {
type: Number
},
discount: {
type: Number
},
details: {
type: String,
trim: true
}
}, {
toJSON: { virtuals: true },
toObject: { virtuals: true }
});
设置虚拟架构
itemsSchema.virtual('totalPrice').get(function() {
const sub_total = this.price + this.shipping;
return (sub_total - ( ( sub_total / 100 ) * this.discount )).toFixed(2)
});