mongoose在一个对象中填充?

我不知道如何填充下面的示例架构,或者甚至是可能的。 在下面的对象中可以引用吗? 如果可以的话,你将如何填充它? 例如.populate('map_data.location');

 var sampleSchema = new Schema({ name: String, map_data: [{ location: {type: Schema.Types.ObjectId, ref: 'location'}, count: Number }] }); 

或者我将不得不有两个单独的arrays的位置和计数像这样:

 // Locations and counts should act as one object. They should // Be synced together perfectly. Eg locations[i] correlates to counts[i] locations: [{ type: Schema.Types.ObjectId, ref: 'location'}], counts: [Number] 

我觉得第一个解决scheme是最好的,但我不完全确定如何在Mongoose中使用它。

非常感谢您的帮助!

第一个解决scheme是可能的。

Mongoose目前有一些限制( 见这张票 )填充embedded式文档的多个级别,但是非常善于理解单个文档中的嵌套path – 在这种情况下你要做的是什么。

示例语法是:

YourSchema.find().populate('map_data.location').exec(...)

其他function,例如在path上指定getters / setters,orderBy和where子句等也可以接受嵌套的path,就像这个文档中的例子:

 personSchema.virtual('name.full').get(function () { return this.name.first + ' ' + this.name.last; }); 

mongoose在内部分割string,并为你sorting。

第一个选项是好的,但如果有人会遇到问题map_data.location – Mongoose返回空数组而不是对象 – 我发现这将工作:

 .populate({ path: 'map_data.location', model: 'Location' }) 

第一个select是最好的。 “count”是对象“map_data”的一部分。