javascript - TypeError on static method of mongoose model -
i'm using node.js along mongodb driver mongoose 3.6.1. 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 separate controller, do
controllers/another.js
var user = require("../models/user").model; function foo() { user.dosomething(); }
and 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 dump user
object can see method there, expected. relevant part of dump confirming that
... schema: { statics: { dosomething: [function] } ...
any idea on i'm doing wrong?
you need set static method before create model:
userschema.statics.dosomething = function () { var user = mongoose.model('user'); // think 'this' points 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, use mongoose terminology, "compiled" schemas. once created model, changes schema aren't propagated model that's derived it.
Comments
Post a Comment