Bur*_*rak 5 mongoose mongodb node.js
我有以下架构.
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 })
Run Code Online (Sandbox Code Playgroud)
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
}
}
})
Run Code Online (Sandbox Code Playgroud)
我无法获取this.location.place.name值,因为this.location.place是一个引用,而不是填充.我该如何访问此值?
小智 2
您是否确定在查询时调用.populate() ?否则,Mongoose 将不知道要拉入引用对象。例子:
ItemModel.findOne().populate('place').exec(function (err, item) {
console.log(item.ranking_in_place)
})
Run Code Online (Sandbox Code Playgroud)