Mongoose:如何从虚拟 getter 访问填充字段?

hic*_*nja 6 mongoose node.js mongoose-populate mongoose-schema

我有几个架构:

var parentSchema = new Schema({name: String});
var childSchema = new Schema({
    name: String,
    parent: {type: Schema.ObjectId, ref: 'Parent'}
});
Run Code Online (Sandbox Code Playgroud)

我希望能够调用Child.find().populate('parent')然后使用以下虚拟 getter:

childSchema.virtual('url').get(function () {
    return "/" + this.parent.name + "/" + this.name
});
Run Code Online (Sandbox Code Playgroud)

但是,当我调用find().populate(),然后将结果子项传递给我的视图并尝试使用时child.url,我总是parent.name设置为未定义。我究竟做错了什么?

Fre*_*tem 0

我知道这是一个老问题,但你可以尝试以下方法:

childSchema.virtual('url').get(function () {
    this.populate("parent");
    return "/" + this.parent.name + "/" + this.name
});
Run Code Online (Sandbox Code Playgroud)

官方文档中有提到这里。