Schemas with subschemas in mongoose

justin

While working on one of my many side projects in node.js I came across a problem I felt was common enough to warrant a blog post. I wanted a schema property to reference another schema. Lets looks at some code

Example without subschemas


/* staff.js */
    var 
        mongoose = require('mongoose')
        , Schema = mongoose.Schema
    ;
    
    var staffSchema = new Schema({
        name:  String,
        job: String,
        comments: String, 
    });
    
    module.exports = mongoose.model('staff', staffSchema);

The "staffSchema" above is a simple definition to hold employee data. All three are "Strings" but this isn't right! A staff member should be able to have multiple comments associated with them, and this is where subschemas come in.

Example with subschema


/* staff.js */
    var 
        mongoose = require('mongoose')
        , Schema = mongoose.Schema
        , comments = require('./comments')      // Include comments schema
    ;

    var staffSchema = new Schema({
         name: String,                        
         job: String,
         comments: [comments.schema],       // NOTICE the .schema!!!
    });
    
    module.exports = mongoose.model('staff', staffSchema);

Notice the change of "comments" from "String" to [comments.schema], this is the reference to the comments schema which we will define in comments.js as seen below

    
/* comment.js */
    
    var 
        mongoose = require('mongoose')
        , Schema = mongoose.Schema
        , ObjectId = Schema.ObjectId
    ;

    var commentSchema = new Schema({
        date: Date,
        person: String,
        comment: String
    });
    
    module.exports = mongoose.model('comment', commentSchema);

And thats it!

comments powered byDisqus