我有以下架构。
var ItemSchema = new Schema({
name : String
,location: {
address: { type: String, default:''},
geolocation: {longitude: Number, latitude:Number},
place : {type: Schema.Types.ObjectId, ref:'Place'}
},
ranking_in_place : Number })
Place 是对具有名称、城市、国家等字段的 Place 架构的引用。
我想为ranking_summary创建一个虚拟:
ItemSchema.virtual('ranking_summary').get(function() {
if(this.ranking_in_place <= 5){
if(this.ranking_in_place == 1){
return "Most popular item" + " in " + this.location.place.name
}
}
})
我无法获取 this.location.place.name 值,因为 this.location.place 是一个引用,而不是填充。我怎样才能访问这个值?
最佳答案
您确定在查询时调用 .populate() 吗?否则,Mongoose 将不知道拉入引用对象。示例:
ItemModel.findOne().populate('place').exec(function (err, item) {
console.log(item.ranking_in_place)
})
关于node.js - 如何在 Mongoose 的虚拟方法中填充引用字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13950171/