mongoose schema creation

One defines Schema so application understands how to map data from the MongoDB into JavaScript objects. Schema is a part of application. It has nothing to do with database. It only maps database into JavaScript objects. So yes – if you want to have nice mapping you need to run this code in every application that needs it. It also applies to getters/setters/validations/etc.

Note however that doing this:

var mongoose = require('mongoose');
var Schema = mongoose.Schema; // <-- EDIT: missing in the original post
var Comments = new Schema({
    title     : String
  , body      : String
  , date      : Date
});
mongoose.model("Comments", Comments);

will register Schema globaly. This means that if the application you are running is using some exterior module, then in this module you can simply use

var mongoose = require('mongoose');
var Comments = mongoose.model("Comments");
Comments.find(function(err, comments) {
    // some code here
});

(note that you actually need to register the Schema before using this code, otherwise an exception will be thrown).

However all of this works only inside one node session, so if you are running another node app which needs the access to the Schema, then you need to call the registration code. So it is a good idea to define all Schemas in separate files, for example comments.js may look like this

var mongoose = require('mongoose');
var Schema = mongoose.Schema; // <-- EDIT: missing in the original post

module.exports = function() {
    var Comments = new Schema({
        title     : String
      , body      : String
      , date      : Date
    });
    mongoose.model("Comments", Comments);
};

then create file models.js which may look like this

var models = ['comments.js', 'someothermodel.js', ...];

exports.initialize = function() {
    var l = models.length;
    for (var i = 0; i < l; i++) {
        require(models[i])();
    }
};

Now calling require('models.js').initialize(); will initialize all of your Schemas for a given node session.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)