Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError on static method of mongoose model

I'm using node.js along with the MongoDb driver Mongoose 3.6.1. This is my schema definition:

models/user.js

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

controllers/another.js

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?

like image 720
Gabriele Petronella Avatar asked Dec 09 '22 15:12

Gabriele Petronella


1 Answers

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.

like image 70
robertklep Avatar answered Dec 11 '22 09:12

robertklep