使用 Mongoose population 之间是否有任何性能差异(查询的处理时间)?和直接对象包含?什么时候应该使用?
Mongoose 种群示例:
var personSchema = Schema({
_id : Number,
name : String,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
_creator : { type: Number, ref: 'Person' },
title : String,
});
var personSchema = Schema({
_id : Number,
name : String,
stories : [storySchema]
});
var storySchema = Schema({
_creator : personSchema,
title : String,
});
最佳答案
首先要了解 Mongoose 种群,它并不神奇,而只是一种方便的方法,可以让您检索相关信息,而无需您自己动手。
该概念主要用于您决定需要将数据放在单独的集合中而不是嵌入该数据的情况,并且您的主要考虑因素通常应该是文档大小或相关信息经常更新的情况维护嵌入式数据很笨拙。
“非魔法”部分是,本质上发生在幕后的事情是,当您“引用”另一个来源时,populate 函数会对该“相关”集合进行额外的查询/查询,以便“合并”父项的这些结果您已检索的对象。您可以自己执行此操作,但该方法是为了方便简化任务。显而易见的“性能”考虑是没有一次到数据库(MongoDB 实例)的往返来检索所有信息。总是不止一个。
作为示例,取两个集合:
{
"_id": ObjectId("5392fea00ff066b7d533a765"),
"customerName": "Bill",
"items": [
ObjectId("5392fee10ff066b7d533a766"),
ObjectId("5392fefe0ff066b7d533a767")
]
}
{ "_id": ObjectId("5392fee10ff066b7d533a766"), "prod": "ABC", "qty": 1 }
{ "_id": ObjectId("5392fefe0ff066b7d533a767"), "prod": "XYZ", "qty": 2 }
var order = db.orders.findOne({ "_id": ObjectId("5392fea00ff066b7d533a765") });
order.items = db.items.find({ "_id": { "$in": order.items } ).toArray();
{
"_id": ObjectId("5392fea00ff066b7d533a765"),
"customerName": "Bill",
"items": [
{ "_id": ObjectId("5392fee10ff066b7d533a766"), "prod": "ABC", "qty": 1 },
{ "_id": ObjectId("5392fefe0ff066b7d533a767"), "prod": "XYZ", "qty": 2 }
]
}
db.orders.findOne({ "_id": ObjectId("5392fea00ff066b7d533a765") });
- Note that since this was originally written MongoDB introduced the
$lookup
operator which does indeed perform "joins" between collections on the server. For the purposes of the general discussion here, whist "better" in most circumstances that the "multiple query" overhead incurred bypopulate()
and "multiple queries" in general, there still is a "significant overhead" incurred with any$lookup
operation.The core design principle is "embedded" means "already there" as opposed to "fetching from somewhere else". Essentially the difference between "in your pocket" and "on the shelf", and in I/O terms usually more like "on the shelf in the library downtown", and notably further away for network based requests.
关于node.js - Mongoose 填充与对象嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24096546/