mongoose Schema设置virtual属性不起作用
发布于 9 年前 作者 carlisliu 8836 次浏览 最后一次编辑是 8 年前 来自 问答
var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    moment = require('moment');


var OrderDetailSchema = new Schema({
    category_id: {type: String},
    category_name: {type: String},
    product_id: {type: String},
    product_name: {type: String},
    product_price: {type: Number},
    product_qty: {type: Number}
});

mongoose.model('OrderDetail', OrderDetailSchema);

var OrderSchema = new Schema({
    no: {type: String, unique: true},
    customer_id: {type: String},
    customer_name: {type: String},
    customer_tel: {type: String},
    customer_address: {
        street: String,
        city: String,
        country: String},
    details: [OrderDetailSchema],
    memo: {type: String},
    create_at: {type: Date, default: Date.now}
});

OrderSchema.virtual('order_date').get(function () {
    console.log('1233333333333333333333333');
    console.log(this.create_at);
    return moment(this.create_at).format('YYYY-MM-DD');
});

OrderSchema.virtual('total').get(function () {
    var sum = 0;
    console.log('1233333333333333333333333');
    return sum;
});

mongoose.model('Order', OrderSchema);
\n```
代码如上,查询的时候查不出设置的order_date和total属性,console的内容也没输出,是什么原因,mongoose还有什么特殊的配置吗?
6 回复

试试这个

new Schema({
    category_id: {type: String},   
    product_qty: {type: Number}
},{
  toJSON: {virtuals: true}
});

@p412726700 thanks,解决了,还有这配置

@carlisliu 没用过这个属性,是不是楼上说的加上option就可以了?~还是有其他要求- -,以前的项目很多废字段存入数据库了- -~正好要研究一下这个

Note that if the resulting record is converted to an object or JSON, virtuals are not included by default. Pass virtuals : true to either toObject() or to toJSON() to have them returned.

来自mongoose文档

@koroshi 是的, Note that if the resulting record is converted to an object or JSON, virtuals are not included by default. Pass virtuals : true to either toObject() or to toJSON() to have them returned.

https://cnodejs.org/topic/5516bdb2e26684ed7ff21e48

回到顶部