猫鼬填充在一个对象内? [英] Mongoose populate within an object?

查看:73
本文介绍了猫鼬填充在一个对象内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何填充下面的示例架构,甚至可能.引用可以在如下所示的对象内吗?如果可以,您将如何填充它?例如. .populate('map_data.location');?

I'm not sure how to populate the sample schema below or if it is even possible. Can a reference be within an object like below? If you can, how would you populate it? E.g. .populate('map_data.location');?

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

或者我将不得不具有两个单独的数组来进行定位和计数,如下所示:

Or will I have to have two separate arrays for location and count like so:

// 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]

我觉得第一个解决方案是最好的,但是我不确定如何在Mongoose中使用它.

I feel like the first solution would be the best, but I'm not entirely sure how to get it working within Mongoose.

非常感谢您的帮助!

推荐答案

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

The first solution is possible.

猫鼬当前有局限性(在此处查看此票证)可填充多层嵌入式文档,但是 非常擅长理解单个文档中的嵌套路径-在这种情况下您要执行的操作.

Mongoose currently has limitations (see this ticket here) populating multiple levels of embedded documents, however is very good at understanding nested paths within a single document - what you're after in this case.

示例语法为:

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

其他功能(例如,在路径,orderBy和where子句上指定getters/setters)也接受嵌套的路径,例如文档:

Other features, such as specifying getters / setters on paths, orderBy and where clauses, etc. also accept a nested paths, like this example from the docs:

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

内部猫鼬在点处将字符串分开,并为您整理所有内容.

Internally Mongoose splits the string at the dots and sorts everything out for you.

这篇关于猫鼬填充在一个对象内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆