16

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.

Artur
  • 347
  • 1
  • 2
  • 11
  • 1
    That dupe q/a doesn't directly address seperate models, just embedded schema. This must have been asked already though... – Matt Feb 17 '17 at 07:51
  • 1
    You could improve the question by using the Mongoose terminology, i.e. "Populating by reference" – Paul Feb 18 '17 at 00:02

1 Answers1

15

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

Neutrosider
  • 562
  • 3
  • 12