我目前遇到了路由器内的问题。 我导出该函数,如以下代码所示。
这是我的模型:
"use strict";
var mongoose = require('mongoose');
var bcrypt = require("bcryptjs");
var Schema = mongoose.Schema;
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
gender: {
type: String,
required: true
},
country: {
type: String,
required: true
},
confirm: {
type: Number
},
confirmcode: {
type: String
},
ip: {
type: String
},
signup: {
type: Date,
default : Date.now
},
voice: {
type: String
},
steam: {
type: String
},
steamid: {
type: String
},
steamlink: {
type: String
},
battletag: {
type: String
},
showsteam: {
type: Number
},
showbnet: {
type: Number
},
birthdate: {
type: Date,
required: true
},
language: {
type: String
}
});
var User = module.exports = mongoose.model('User',UserSchema);
module.exports.createUser = function(newUser, callback){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
}
module.exports.comparePw = function(canPw, hash, callback){
bcrypt.compare(canPw, hash).then((res) => {
callback(null,res);
});
}
module.exports.findUserById = function(id,callback){
User.findById(id,callback);
}
module.exports.getGamer = function(count,callback){
User.count(count,callback);
}
module.exports.findUsername = function(uname, callback){
var query = {username:uname};
User.findOne(query,callback);
}
module.exports.findEmail = function(email, callback){
var query = {email:email};
User.findOne(query,callback);
}
这是我的路由器:
var User = require("../../model/user");
module.exports = function(router){
router.get("/user", function(req, res){
var user = new User();
user.getGamer(function(err,response){
if(err){
throw err;
}else{
res.json(response);
}
});
});
}
我得到的错误是:
TypeError: user.getGamer is not a function
但我不知道为什么。任何人都可以帮助我吗?
最佳答案
您需要将模型方法附加到架构,而不是模型。然后这些方法将在您的模型实例上可用。请参阅this post了解更多。
UserSchema.methods.getGamer = function(newUser, callback) ...
关于javascript - Model.function 不是路由器内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43770424/