Saving Sub-Documents With Mongoose
I'm pretty new to mongoDB and the popular ORM Mongoose. And I just spent way too much time trying to figure out the proper way to save sub-documents in mongoose. The mongoose documentation shows you how to assign values to each property of a sub-document when pushing it onto the sub-document array, but how often will you do that? If you are using Mongoose, you probably have a model for the sub-document and you are probably passing that around between your controllers and models. So how does one persist a model of a sub-document to the parent document? Here is an example:
First, the model and schema stuff:
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var childSchema = new Schema({
foo: String
});
var Child = mongoose.model('Child',childSchema);
model['Child'] = Child;
var parentSchema = new Schema({
parent_foo: String
,children: [model["Child"].schema]
});
var Parent = mongoose.model('Parent',parentSchema);
model['Parent'] = Parent;
And here is an example of how to save the sub-document (assuming myParent is an object of type Parent and myChild is an object of type Child):
myParent.children.push(myChild);
References:
http://mongoosejs.com/docs/subdocs.html
https://groups.google.com/forum/?fromgroups=#!topic/mongoose-orm/IIaVEHcEDTw
Written by Edmund Kump
Related protips
3 Responses
Why did you need this line of code?
model['Child'] = Child;
Couldn't you just do this in the parent?
,children: [Child.schema]
bighi, you don't need it.
side note--i had been stuck because i was (apparently) misreading the docs, thinking that "children" was somehow an actual method that was available. Wasn't 'til i saw your full example that they were just referring to the specific child field (meaning you can have multiple children and refer to them separatly---DERP)
The mongoose document about this feature is too damn bad explained. Reading this article, I understand that you can't add a children schema to it's parent without create a children model first. That should be explained by official mongoose docs.