如何在Mongoose中填充虚拟方法中的引用字段?
我有以下架构。
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 })
地方是具有名称,城市,国家等字段的地方架构的参考。
我想为ranking_summary创build一个虚拟的:
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) })
Model.find().populate(path, fields, conditions, options);
所以你可以使用的选项
{ sort: 'order' } // ascending { sort: [['order', 1 ]] } // ascending { sort: [['order', 'asc' ]] } // ascending { sort: [['order', 'desc' ]] } // ascending { sort: [['order', -1 ]] } // descending { sort: [['order', 'desc' ]] } // descending { sort: [['order', 'descending' ]] } // descending
我认为没有直接的方法来做到这一点。 你可以通过跟踪钩子来达到这个目的。 [阅读更多]
这是一个示例代码。 我需要计算由video组成的教程的总时间。 所以,我不得不填充video,然后使用他们的持续时间来计算教程的总时间。
tutorialSchema.pre('findOne', function (next) { this.populate('videos'); // now available as this.ratings in this schema next(); }); tutorialSchema.virtual('totalTime').get(function () { let times = []; times = this.videos.map((v) => { return v.duration; }); if(times.length === 0) return 0; let totalTime = times.reduce((sum, time) => { return sum + time; }); return totalTime; });