Node.js Mongoose 静态函数未被调用

Node.js Mongoose static function not getting called

最近我一直在尝试重写我的 node.js express 应用程序,使其更符合 mvc 原则。我也一直在尝试合并猫鼬。我在调用猫鼬模型上的静态函数时遇到问题。

userSchema.statics.findDuplicates = function (cb) {
    console.log("Duplicates called");

    this.findOne({ email: this.email }, function(err, result){
        if (err) throw err;
        if (result) {
            cb("A user with this email has already been created.");
        } else {
            cb("");
        }
    });
}

现在的问题是我稍后要使用此架构导出模型,因此所有这些都包含在一个文件中:

module.exports = mongoose.model('User', userSchema);

当我稍后在控制器中调用它时,(显然需要事先启动模型):

user.findDuplicates(function(result){

    if (result) {
        res.send("Selle e-mailiga kasutaja on juba loodud.");
        console.log("Duplicates");
    } else {
        user.save();
        res.send("Kasutaja loodud.");
        console.log("User created with password.")
    }
});

它永远不会被调用。 Node 告诉我它接受了 post,但是出现了 500 内部服务器错误,并且 findDuplicates 中的 "Duplicates called" 没有出现在控制台中。这里出了点问题,我不知道如何解决。

编辑:完整控制器代码:

var express = require('express');
var router = express.Router();

var User = require("../models/user.js");

router.get('/', function(req, res, next) {
    res.render('users',{title: "Lisa kasutaja"});
});

router.post('/', function(req, res, next) {
    var query = req.body;
    var message = "";

    console.log("Post recieved " + JSON.stringify(query));

    if (query.password != query.repeatPassword){
        res.send("Paroolid ei ole võrdsed.");
        console.log("Passwords don't match");
    } else {
        var user = new User({
            firstName: query.firstName,
            lastName: query.lastName,
            telephone: query.telephone,
            email: query.email,
            password: query.password
        });

        console.log("User created");

        user.findDuplicates(function(result){

            if (result) {
                res.send("Selle e-mailiga kasutaja on juba loodud.");
                console.log("Duplicates");
             } else {
                user.save();
                res.send("Kasutaja loodud.");
                console.log("User created with password.")
            }
        });
    }

});

module.exports = router;

您的问题在于您在模型实例中调用静态方法,这是不正确的。请参阅以下差异:

// if you define a static method
userSchema.statics.findDuplicates = function (cb) {
  // do your stuff
}

// you call it this way
var User = require("../models/user.js");
User.findDuplicates(function (result) {
  // do your stuff
});

// if you define an instance method
userSchema.methods.findDuplicates = function (cb) {
  // do your stuff
};

// you call it this way (on an instance of your model)
var User = require("../models/user.js");
var user = new User({
      firstName: query.firstName,
      lastName: query.lastName,
      telephone: query.telephone,
      email: query.email,
      password: query.password
    });
user.findDuplicates(function (result) {
  // do your stuff
});