Mongoose subdocuments vs nested schema
I'm curious as to the pros and cons of using subdocuments vs a deeper layer in my main schema:
var subDoc = new Schema({
name: String
});
var mainDoc = new Schema({
names: [subDoc]
});
or
var mainDoc = new Schema({
names: [{
name: String
}]
});
I'm currently using subdocs everywhere but I am wondering primarily about performance or querying issues I might encounter.
Solution 1:
According to the docs, it's exactly the same.
However, using a Schema would add an _id
field as well (as long as you don't have that disabled), and presumably uses some more resources for tracking subdocs.
Alternate declaration syntax
New in v3 If you don't need access to the sub-document schema instance, you may also declare sub-docs by simply passing an object literal [...]
Solution 2:
If you have schemas that are re-used in various parts of your model, then it might be useful to define individual schemas for the child docs so you don't have to duplicate yourself.