Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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.

like image 446
Artur Avatar asked Feb 17 '17 05:02

Artur


1 Answers

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

like image 85
Neutrosider Avatar answered Oct 05 '22 10:10

Neutrosider