Search code examples
node.jsmongodbmongoosehardcode

Is there a way to avoid hard coding with Mongoose?


Consider the following code, where 'Team' is a mongoose model.

var Team = mongoose.model( 'Team' );
Team.find({'GroupName':gname}, function (err, teams) {
   // Some code
}

How do I get rid of this hard coding where I hard code 'GroupName':gname during selection in mongo?


Solution

  • One approach is to define static methods on your model that expose a DAO interface that encapsulates these sort of details:

    Team.js

    teamSchema.statics.findByGroupName = function (gname, cb) {
        this.find({ GroupName: gname }, cb);
    };
    ...
    

    Other.js

    Team.findByGroupName(gname, function (err, teams) {
       // Some code
    });