猫鼬嵌套模式与嵌套模型 [英] Mongoose nested schema vs nested models
问题描述
在架构(子文档)中嵌套架构与创建两个单独的模型并引用它们之间有什么区别?它们的性能如何?
What is the difference between nesting schema in schema (subdocuments) vs creating two separate models and referring to them, What about their performance?
子文档:
const postSchema = new Schema({
title: String,
content: String
});
const userSchema = new Schema({
name: String,
posts: [postSchema]
});
module.export = mongoose.model('User', userSchema);
嵌套模型(通过引用填充):
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);
编辑:这不是重复的问题.
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.
推荐答案
使用子文档时,实际上您在父文档中有一个数据副本,这使您可以在其中获取所有文档+子文档数据.一个查询.
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.
简而言之:子文档实际上嵌套了数据,而您的嵌套模型"仅通过其ID引用了它们
In short: subdocuments actually nest the data, and your "nested models" only reference them via their id
这篇关于猫鼬嵌套模式与嵌套模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!