【问题标题】:Mongoose nested schema vs nested modelsMongoose 嵌套模式与嵌套模型
【发布时间】:2017-07-06 12:35:15
【问题描述】:

在模式(子文档)中嵌套模式与创建两个单独的模型并引用它们有什么区别,它们的性能如何?

子文档:

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

编辑:这不是重复的问题。

在这个问题中:Mongoose subdocuments vs nested schema - mongoose 子文档和嵌套模式完全一样。 但是嵌套模型在数据库中创建了一个单独的集合。 我的问题是嵌套模式与嵌套模型的区别是什么,而不是子文档与嵌套模式。

【问题讨论】:

  • 那个 dupe q/a 不直接解决单独的模型,只是嵌入模式。这肯定已经被问过了......
  • 您可以使用 Mongoose 术语改进问题,即“通过引用填充”

标签: node.js mongodb mongoose


【解决方案1】:

使用子文档时,您实际上在父文档中拥有数据的副本,这允许您在单个查询中获取所有文档 + 子文档数据。

使用“嵌套模型”时,您实际上并不是在嵌套它们,而是从父模型引用到子模型。在这种情况下,您必须使用population,这意味着您无法在单个查询中获取所有数据。

简而言之:子文档实际上嵌套了数据,而您的“嵌套模型”仅通过其 id 引用它们

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-06
    • 2015-03-29
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多