How to Use mongoose Virtual Attribute

  mongodb, question


In the above example, a virtual field was defined by virtual(‘c’), but in the later find () query, the document found did not contain this virtual field c. where did this virtual field appear after it was defined?

The queried document object should have this field. You can see it by trying to print Result. C. As to why the document object cannot be directly printed, mongoose’s official website has this sentence:

If you use toJSON() or toObject() (or use
JSON.stringify() on a mongoose
document) mongoose will not include
virtuals by default. Pass { virtuals: true }
to either toObject() or toJSON().

You can

UserSchema.set('toJSON', { virtuals: true })



You can see it