Node.js Wiki
Advertisement


Where Mongoose starts to get fun is with nested schemas. Say you have robots made of various parts. You can define a Parts schema and nest it inside your robots schema. Note that you can't, say, create five or six different schemae and slot it into a single field - no polymorphism here.

var mongoose = require('mongoose');
var db = require('./db');
var parts_module = require('./parts');

module.exports = {
    _schema: null,
    
    _schema_def: {
         _id: String
       , name: String
       , parts: [parts_model.schema()]
       //, address: address.schema()
    },
    
    schema: function(){
        if (!module.exports._schema){
            module.exports._schema = new mongoose.Schema(module.exports._schema_def);
        }
        
        return module.exports._schema;
    },
    
    _model: null,
    
    model: function(new_instance){
        if (!module.exports._model){
            var schema = module.exports.schema();
         //   console.log('schema for users');
         //   console.log(schema);
            mongoose.model('Robots', schema);
            module.exports._model = mongoose.model('Robots');
        }
        
        return new_instance ?
           new module.exports._model() :
           module.exports._model;
    }
}

... and here is the parts model.

var mongoose = require('mongoose');

module.exports = {
    _schema: null,

    _schema_def: {
         _id: String
       , name: String
       , weight: Number
       , part_number: String
    },
    
    schema: function(){
        if (!module.exports._schema){
            module.exports._schema = new mongoose.Schema(module.exports._schema_def);
        }
        
        return module.exports._schema;
    },
    
    _model: null,
    
    model: function(new_instance){
        if (!module.exports._model){
            var schema = module.exports.schema();
         //   note- 
            mongoose.model('RobotParts', schema);
            module.exports._model = mongoose.model('RobotParts');
        }
        
        return new_instance ?
           new module.exports._model() :
           module.exports._model;
    }
}

Note that - for completeness' sake - I provide model methods for my parts model, the point of this module is to provide a schema for robots to use - I don't intend to store robot parts outside of the robots collection.

Since the parts schema is nested you don't have to do any activerecord schenanigans with it - you can just pass it objects and Mongoose will cast them nicely.

var robot_module = require('./../model/robot');

var robot = robot_module.model(true);

robot.parts = [{part_number: 1415, name: 'Laser Gun', weight: 15},
{part_number: 214526, name: 'treadmill', weight: 2000} ...
];

robot.save();
Advertisement