猫鼬在一个物体内填充?

Rya*_*ott 17 mongoose node.js

我不确定如何填充下面的示例模式或甚至是否可能.引用可以在下面的对象中吗?如果可以的话,你会如何填充它?比如.populate('map_data.location');

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

或者我必须有两个单独的数组用于位置和计数,如下所示:

// Locations and counts should act as one object. They should
// Be synced together perfectly.  E.g. locations[i] correlates to counts[i]
locations: [{ type: Schema.Types.ObjectId, ref: 'location'}],
counts: [Number]
Run Code Online (Sandbox Code Playgroud)

我觉得第一个解决方案是最好的,但我不完全确定如何让它在Mongoose中运行.

非常感谢您的帮助!

Jed*_*son 22

第一种解决方案是可能的.

猫鼬目前有限制(在这里看到这张票)填充嵌入文档的多层次,不过在一个文档中了解嵌套的路径非常好-你在这种情况下,后在做什么.

示例语法是:

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

其他功能,例如在路径上指定getter/setter,orderBy和where子句等,也接受嵌套路径,如文档中的此示例所示:

personSchema.virtual('name.full').get(function () {
  return this.name.first + ' ' + this.name.last;
});
Run Code Online (Sandbox Code Playgroud)

内部的猫鼬将弦线分成点,然后为你排序.


kko*_*ski 10

第一个选项没问题,但如果有人遇到该查询的问题map_data.location- Mongoose返回空数组而不是对象 - 我发现这样可行:

.populate({
     path: 'map_data.location',
     model: 'Location'
})
Run Code Online (Sandbox Code Playgroud)