猫鼬填充在一个对象中

猫鼬填充在一个对象中

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

问题描述

我不确定如何填充下面的示例架构,或者是否可能.引用可以在像下面这样的对象内吗?如果可以,你会如何填充它?例如..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 目前有限制(在此处查看此票)填充多个级别的嵌入式文档,但是 非常擅长理解单个文档中的嵌套路径 - 在这种情况下您所追求的是什么.

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(...)

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

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;
});

Mongoose 内部会在点处拆分字符串并为您整理所有内容.

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

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

08-24 18:52