Reputation: 4862
If I have the following mongoose models:
// child.model.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
childSchema = new Schema({
name: String,
age: Number
}, {collection: 'children'});
module.exports = mongoose.model('Child', childSchema);
//parent.model.js
var mongoose = require('mongoose'),
Child = require('./child.model.js'),
Schema = mongoose.Schema,
parentSchema = new Schema({
name: String,
children: [Child.schema]
});
module.exports = mongoose.model('Parent', parentSchema);
Would this mean I would then have two collections, one called 'parents' and one called 'children'?
As I currently understand it the above code creates a nested document structure whereby the Child
objects exist only within the collection of Parent
documents. However, I'm getting confused by the {collection: 'name'}
option that you can pass to the Schema
constructor. Is this option just ignored when creating sub-documents like this?
Upvotes: 0
Views: 74
Reputation: 34667
There are two kinds of subdocs - Embedded and Referenced. This is a Mongoose-level classification. At MongoDB level it's just Collections and Documents.
The difference between Embedded and Referenced docs in Mongoose is that the former is akin to having the child schema "embedded" in the parent. I.e. as far as MongoDB is concerned it (Parent) is just a one big document.
Whereas in referenced docs the Parent document only stores the child document's ObjectID, i.e. the child document is "referenced", and it's left up to you to "populate" the entire document.
What you're using children: [Child.schema]
is the syntax of an Embedded document.
Would this mean I would then have two collections, one called 'parents' and one called 'children'?
So you'll have only 1 collection in MongoDB.
However, I'm getting confused by the {collection: 'name'} option that you can pass to the Schema constructor. Is this option just ignored when creating sub-documents like this?
That option is just so that if you were to actually create a model from that schema, it uses the name you provided instead of automatically inferring.
Upvotes: 2