gpt4 book ai didi

node.js - Mongoose userModel 未定义

转载 作者:太空宇宙 更新时间:2023-11-04 00:06:04 28 4
gpt4 key购买 nike

我对 Nodejs 和 mongoDB 还很陌生。我已经创建了注册和用户架构,但它无法识别this并发送以下错误:

ReferenceError: userModel is not defined

当我跟踪错误时,我发现它无法识别this关键字。

这是user.js代码:

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

var bcrypt = require('bcrypt');

var userSchema = new Schema({
teamName: {
type: String,
unique: true,
trim: true,
required: true
},
faculty: {
type: String,
required: true
},
email: {
required: true,
unique: true,
trim: true,
type: String
},
password: {
required: true,
type: String
},
score: {
type: Number,
default: 0
}
});

userSchema.pre('save', function(next) {
var user = this;
bcrypt.hash(user.password, 10, (err, hash) => {
if (err) return next(err)
user.password = hash;
next();
});
})

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

server.js

router.post('/register', (req, res) => {
var newUser = {
teamName: req.body.teamName,
faculty: req.body.faculty,
email: req.body.email,
password: req.body.password
}
userModel.create(newUser, (err, user) => {
if (err) {
console.log('[Registratoin]: ' + err);
} else {
console.log(user)
console.log('[Registration]: Done');
// req.session.userID = user._id;
res.redirect('/scoreboard')
}
});
});

最佳答案

模型中预保存 Hook 中的 this 关键字不是问题。

ReferenceError: userModel is not defined

ReferenceError: "x" is not defined意味着 userModel 在您调用它的范围内未定义。 (因此您引用了一个不存在的值)

I have include it like var userModel = require('the_path')

正如您所要求的并正确导出userModel。我会仔细检查您导入模块的路径。

关于node.js - Mongoose userModel 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52248729/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com