I'm using node.js along with the MongoDb driver Mongoose 3.6.1. This is my schema definition:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var userSchema = new Schema({
...
});
module.exports = {
model : mongoose.model('User', userSchema)
};
userSchema.statics.doSomething = function () {
console.log("I'm doing something");
}
Then in a separate controller, I do
var User = require("../models/user").model;
function foo() {
User.doSomething();
}
and I get the following error
[TypeError: Object function model(doc, fields, skipId) {
if (!(this instanceof model))
return new model(doc, fields, skipId);
Model.call(this, doc, fields, skipId);
} has no method 'doSomething']
However, if I dump the User
object I can see the method there, as expected. This is the relevant part of the dump confirming that
...
schema:
{ statics:
{ doSomething: [Function] }
...
Any idea on what I'm doing wrong?
You need to set the static method before you create your model:
userSchema.statics.doSomething = function () {
var User = mongoose.model('User');
// I think 'this' also points to the User model here:
// var User = this;
// var user = new User(...);
console.log("I'm doing something");
}
module.exports = {
model : mongoose.model('User', userSchema)
};
Models are, to use the Mongoose terminology, "compiled" from schemas. Once you created a model, any changes to the schema aren't propagated to the model that's derived from it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With