Skip to content

Instantly share code, notes, and snippets.

@bayleedev
Last active December 26, 2019 09:11
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bayleedev/9d32df6477dae2dbc38a to your computer and use it in GitHub Desktop.
Save bayleedev/9d32df6477dae2dbc38a to your computer and use it in GitHub Desktop.
A better syntax for mongoose instance and static methods.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/foobar');
// bootstrap mongoose, because syntax.
mongoose.createModel = function(name, options) {
var schema = new mongoose.Schema(options.schema);
for (key in options.self) {
if (typeof options.self[key] !== 'function') continue;
schema.statics[key] = options.self[key];
}
for (key in options) {
if (typeof options[key] !== 'function') continue;
schema.methods[key] = options[key];
}
return mongoose.model(name, schema);
};
// Define the model w/ pretty syntax!
var Animal = mongoose.createModel('Animal', {
schema: {
name: String,
type: String
},
self: {
findByType: function(type, cb) {
return this.find({ type: type }, cb);
}
},
findSimilarTypes: function(cb) {
return this.model('Animal').find({ type: this.type }, cb);
}
});
// Interaact with it
var dog = new Animal({ type: 'dog' });
dog.findSimilarTypes(function (err, dogs) {
console.log(dogs); // woof
});
Animal.findByType('dog', function(err, dogs) {
console.log(dogs); // ruff
});
@EnergeticPixels
Copy link

@blain, I am slight confused. Does your bootstrap section belong in same .js file as your define model section? If so, why did you do it this way. I am developing my first professional API (getting paid for it). Got to get it correct the first time.
Tony

@leeya018
Copy link

leeya018 commented Jan 29, 2019

Hi
your code is working great but I still try to understand why its not working for me in the standard way.
I will be happy to know what is the difference behind the scene. because I do not see any.
this is my code .
the error that I am getting is "findSimilarTypes is not a function"

let animalSchema = new mongoose.Schema({
  name: String,
  type: String
});
let Animal = mongoose.model("Animal", animalSchema);


animalSchema.statics.findByType = function(type, cb) {
  return this.find({ type: type }, cb);
};

animalSchema.methods.findSimilarTypes = function(cb) {
  return this.model("Animal").find({ type: this.type }, cb);
};
//invoke : 
dog.findSimilarTypes(function(err, dogs) {
  console.log(dogs); // woof
});

Animal.findByType("dog", function(err, dogs) {
  console.log(dogs); // ruff
});

@leeya018
Copy link

Ok,
just find out my problem
the function should be added to the schema before creating the model

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment