What is the difference between nesting schema in schema (subdocuments) vs creating two separate models and referring to them, What about their performance?
架构(子文档)中的嵌套架构与创建两个单独的模型并引用它们之间有什么区别,它们的性能如何?
subdocuments:
const postSchema = new Schema({
title: String,
content: String
});
const userSchema = new Schema({
name: String,
posts: [postSchema]
});
module.export = mongoose.model('User', userSchema);
nested models (Populating by reference):
嵌套模型(按引用填充):
const postSchema = new Schema({
title: String,
content: String,
author: { type: String, ref: 'User' }
});
module.export = mongoose.model('Post', postSchema);
const userSchema = new Schema({
name: String,
posts: [{ type: Schema.Types.ObjectId, ref: 'Post'}]
});
module.export = mongoose.model('User', userSchema);
Edit: This is not a duplicate question.
编辑:这不是一个重复的问题。
In this question: Mongoose subdocuments vs nested schema - mongoose subdocuments and nested schema is exactly the same. BUT nested models creating a separate collection in database. My question is what is diffrence in nested schema vs nested models, not subdocuments vs nested schema.
在这个问题中:Mongoose子文档与嵌套模式 - mongoose子文档和嵌套模式完全相同。但是嵌套模型在数据库中创建单独的集合。我的问题是嵌套模式与嵌套模型的差异是什么,而不是子文档与嵌套模式。
1 个解决方案
#1
8
When using subdocuments, you actually have a copy of the data within your parent-document, wich allows you to get all the document + sub-document-data in a single query.
使用子文档时,实际上您的父文档中包含数据的副本,这使您可以在单个查询中获取所有文档+子文档数据。
When using "nested models" you're not really nesting them, but referencing from the parent-model to the child-model. In this case you have to use population, which means you can't get all the data in a single query.
使用“嵌套模型”时,您并没有真正嵌套它们,而是从父模型引用到子模型。在这种情况下,您必须使用填充,这意味着您无法在单个查询中获取所有数据。
In short: subdocuments actually nest the data, and your "nested models" only reference them via their id
简而言之:子文档实际上嵌套了数据,而您的“嵌套模型”仅通过它们的id引用它们
#1
8
When using subdocuments, you actually have a copy of the data within your parent-document, wich allows you to get all the document + sub-document-data in a single query.
使用子文档时,实际上您的父文档中包含数据的副本,这使您可以在单个查询中获取所有文档+子文档数据。
When using "nested models" you're not really nesting them, but referencing from the parent-model to the child-model. In this case you have to use population, which means you can't get all the data in a single query.
使用“嵌套模型”时,您并没有真正嵌套它们,而是从父模型引用到子模型。在这种情况下,您必须使用填充,这意味着您无法在单个查询中获取所有数据。
In short: subdocuments actually nest the data, and your "nested models" only reference them via their id
简而言之:子文档实际上嵌套了数据,而您的“嵌套模型”仅通过它们的id引用它们