TypeError by the mongoose model static method

I am 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 reset the User object, I see the way there, as expected. This is the relevant part of the dump, confirming that

 ... schema: { statics: { doSomething: [Function] } ... 

Any idea what I'm doing wrong?

+4
source share
1 answer

Before creating a model, you need to set a static method:

 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 - use Mongoose terminology β€œcompiled” from schemas. After creating the model, any changes in the scheme do not apply to the model obtained from it.

+13
source

Source: https://habr.com/ru/post/1481877/


All Articles