2

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?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Gaurav Goel
  • 325
  • 2
  • 14
  • What hard coding? You realize the arguments are just a JavaScript object don't you? It's not really clear what you are asking here as that is not the best example of avoiding hard coding. – Neil Lunn Jun 10 '14 at 06:04
  • Suppose, I have a file named 'Team.js' where I define a mongoose model. Now, I have another file 'other.js' where I'd like to fetch a Team document from mongo db. Solution A: Now, if I mention 'GroupName' attribute of a model in the 'other.js' file, then it seems I am increasing the coupling. Solution B: I move all the fetching and updation code to the model itself or to a DAO like file. Typing in 'GroupName' every time I need to select it or update it doesn't feel right. – Gaurav Goel Jun 10 '14 at 06:11

1 Answers1

3

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
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Hi Johnny, I too personally am in favor of the same approach. Thanks for your response. – Gaurav Goel Jun 11 '14 at 09:28
  • You might also want to go through [hibernate meta models](https://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/metamodel.html). This seems like an elegant solution. – Gaurav Goel Jun 11 '14 at 09:43