Yashua Yashua - 4 months ago 158
Javascript Question

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.

Answer

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 [...]