Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

node.js - Mongoose: Vritual getter of populated document

I have 2 schemas and schema2 is populating field from schema1 which has a virtual getter. But that virtual getter is not appearing when I populate from schema2.

example code:

schema1 = new Schema({
  comments: [{ type: Array }],
})

schema1.virtual('comment_count').get(function() {
    return this.comments.length
})

schema2 = new Schema({
  post: { type: String },
  people: { type: Schema.Types.ObjectId, ref: 'schema1' }
})  

assuming schema2's model is schema2model

schema2model.find({}).populate('people')

here i do get comments property but I'm not getting comment_count field

question from:https://stackoverflow.com/questions/65860663/mongoose-vritual-getter-of-populated-document

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • There are few ways to access virtual properties, try anything:
  1. Access manually
var docs = schema2model.find({}).populate('people');
console.log(docs[0].people.comment_count);
  1. Access using toObject method
var docs = schema2model.find({}).populate('people');
docs = docs.toObject({ virtuals: true });
console.log(docs);
  1. set toObject: { virtuals: true } property in your schema
let schema1 = new Schema({
  comments: [{ type: Array }]
}, { toObject: { virtuals: true } });
  • call your query after updating your schema
var docs = schema2model.find({}).populate('people');
console.log(docs);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...