Mongoose nested schema versus nested models

What is the difference between the nesting scheme in the scheme (subdocuments) and the creation of two separate models and a reference to them, but how is their effectiveness?

attached documents:

const postSchema = new Schema({ title: String, content: String }); const userSchema = new Schema({ name: String, posts: [postSchema] }); module.export = mongoose.model('User', userSchema); 

nested models (filling in 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 substrates versus nested schema - mongoose subdocuments and nested schema exactly match. BUT nested models create a separate collection in the database. My question is what is the difference in nested schema and nested models, rather than nested documents with nested schema.

+5
source share
1 answer

When using subdocuments, you really have a copy of the data in your parent document, allowing you to get the entire document + subdocument data in one request.

When using "nested models" you do not actually insert them, but refer from the parent model to the child model. In this case, you must use the population , which means that you cannot get all the data in one query.

In short : nested documents actually insert data, and your "nested models" refer only to their identifier

+5
source

Source: https://habr.com/ru/post/1264331/


All Articles