对于猫鼬模型的静态方法的TypeError [英] TypeError on static method of mongoose model

查看:101
本文介绍了对于猫鼬模型的静态方法的TypeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用node.js和MongoDb驱动程序 Mongoose 3.6.1 。这是我的架构定义:

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();
}

我收到以下错误

[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)
};

模型是使用Mongoose术语从模式编译的。创建模型后,对模式的任何更改都不会传播到从中派生的模型。

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.

这篇关于对于猫鼬模型的静态方法的TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆