1 javascript static mongoose node.js
最近我一直试图重写我的node.js表达应用程序更符合mvc原则.我也一直试图加入猫鼬.我在mongoose模型上调用静态函数时遇到问题.
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("");
}
});
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是我后来使用这个模式导出模型,所以这一切都包含在一个文件中:
module.exports = mongoose.model('User', userSchema);
Run Code Online (Sandbox Code Playgroud)
当我后来在控制器中调用它时(显然需要事先启动模型):
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.")
}
});
Run Code Online (Sandbox Code Playgroud)
它永远不会被调用.Node告诉我它接受了一个帖子,但是得到了一个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;
Run Code Online (Sandbox Code Playgroud)
您的问题在于您在模型实例中调用静态方法,这是不正确的.看下面的差异:
// 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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3315 次 |
| 最近记录: |