mongoose使用中查不出定义的virtual字段

定义了指定为virtual属性的post_count字段统计文章数

1
2
3
4
5
6
7
8
9
10
11
12
// model
var TagSchema = new Schema({
name: String,
slug: String,
posts: [{ type:Schema.ObjectId, ref:"Post" }],
created_at: {type: Date, default: Date.now }
});

// virtual
TagSchema.virtual('post_count').get(function(){
return this.posts ? this.posts.length : 0;
});

使用find查询的时候居然查不出post_count出来。查看手册后是因为document 对象的toJSON和toObject方法里面 默认将virtual 属性排除了。 原文是这样的:

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.

需要对Schama做下面的配置:

1
2
TagSchema.set('toJSON', { virtuals: true });
TagSchema.set('toObject', { virtuals: true });