我有一个模特
var OrderSchema = new Schema({
created: {
type : Date,
default: Date.now
}
}):
我希望在检索到此文档时添加字段number_of_days_open字段。我尝试使用虚拟字段
OrderSchema
.virtual('number_of_days_open')
.get(function () {
return moment(this.created).fromNow();
});
但是当我收到订单时
exports.read = function(req, res) {
res.json(req.order);
};
exports.orderByID = function(req, res, next, id) {
Order.findById(id).exec(function(err, order) {
req.order = order;
next();
});
};
我没有得到字段number_of_days_open。当我做的时候,我也不会得到这个领域
exports.list = function(req, res) {
Order.find().sort('-created').exec(function(err, orders) {
if (!err) res.json(orders);
});
};
答案 0 :(得分:3)
OrderSchema.set('toObject', { virtuals: true }) // console.log() statements would
// print the virtual fields.
OrderSchema.set('toJSON', { virtuals: true }); //virtual fields are visible when
//the mongodb
//document is converted into a
//javascript object
//internally or explicitly.