【问题标题】:Model.find() in not a function ExpressJSModel.find() 不是一个函数 ExpressJS
【发布时间】:2017-03-28 16:14:51
【问题描述】:

我正在尝试检查用户是否存在于save 调用的预挂钩中。这是我的模型的架构:

var mongoose    = require('mongoose');
var Schema      = mongoose.Schema;

var empSchema = new Schema({
    name: String,
    img: String,
    info: String,
    mobnum: String,
    email: String,
    likes: [String]
},
{
    collection: "employers"
}
);


empSchema.pre('save', function(next) {
    var self = this;
    empSchema.find({email: self.email}, function(err, docs) {
        if(!docs.length()){
            next();
        }
        else {
            next(new Error("User exists."));
        }
    });
});

module.exports = mongoose.model('Employer', empSchema);

这给了我以下错误:

/home/gopa2000/prog/android_workspace/MobAppsBE/app/models/employer.js:21
    empSchema.find({email: self.email}, function(err, docs) {
              ^

TypeError: empSchema.find is not a function

包.json:

{
  "name": "tjbackend",
  "version": "1.0.0",
  "description": "REST API for backend",
  "dependencies": {
    "express": "~4.5.1",
    "mongoose": "latest",
    "body-parser": "~1.4.2",
    "method-override": "~2.0.2",
    "morgan": "~1.7.0"
  },
  "engines": {
    "node":"6.4.0"
  }
}

对我的问题有什么建议吗?

【问题讨论】:

  • hmm... empSchema 是模型吗?在我看来,它就像一个架构。
  • stackoverflow.com/questions/16882938/… 我正在遵循已接受答案的“更新 2”下的方法。我正在从不同的控制器文件调用 save。
  • 您似乎没有非常密切地遵循上述方法。 User 与 userSchema 不一样
  • 哎哟。你是对的。夜里走得太远了。 :-) 谢谢!

标签: node.js mongodb express mongoose


【解决方案1】:

find() 函数属于model,不属于schema。
您需要生成一个模型并在其上运行 find:

var mongoose    = require('mongoose');
var Schema      = mongoose.Schema;

var empSchema = new Schema({
    name: String,
    img: String,
    info: String,
    mobnum: String,
    email: String,
    likes: [String]
},
{
    collection: "employers"
}
);

var employer = mongoose.model('Employer', empSchema);

empSchema.pre('save', function(next) {
    var self = this;
    employer.find({email: self.email}, function(err, docs) {
        if(!docs.length()){
            next();
        }
        else {
            next(new Error("User exists."));
        }
    });
});

module.exports = employer;

【讨论】:

    猜你喜欢
    • 2016-03-18
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 2022-01-10
    • 2015-11-05
    • 1970-01-01
    相关资源
    最近更新 更多