我正在使用Express,NodeJS和MongoDB进行身份验证/会话。
Mongoose模式如下所示:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: { type: String, required: true, },
email: { type: String, required: true, unique: true, },
password: { type: String, required: true, },
SignUpDate: { type: { type: Date, default: Date.now } },
LastLogin: { type: { type: Date, default: Date.now } },
loggedin: { type: Boolean, required: false, },
attempts: { type: Number },
});
module.exports = mongoose.model("User", userSchema);
注册表单只采取用户名,电子邮件,密码,但我想保存签名更新,上次登录,失败的登录尝试等。
在controller.js文件中,我有路由,这是有问题的路由。
exports.register_post = async (req, res) => {
const { username, email, password } = req.body;
let user = await User.findOne({ email });
if (user) {
req.session.error = "User already exists";
return res.redirect("/register");
}
const hasdPsw = await bcrypt.hash(password, 12);
user = new User({
username,
email,
password: hasdPsw,
SignUpDate,
loggedin: true
});
await user.save();
console.log(user)
res.redirect("/login");
};
在app.js中我有这个
app.post("/register", appController.register_post);
如果我在模式中只使用用户名,电子邮件和密码,那么它都可以工作,并保存到数据库中。
但如上,我得到
“UnhandledPromiserEjectionWarning:ReferenceError:SignUpDate未定义”
如果我在/Register路线上提交注册按钮。另一个问题,如果我想用Mongoose获得时间戳,我是否必须调用date.now()
以及在哪里调用?
或者我必须在用户注册后定义并添加/推送不是用户通过注册后提供的属性(SignUpDate,LastLogin:,Loggedin:,attempts)到模式中?我是新使用猫鼬,通过文件,似乎无法找到如何广告一个时间戳。
一个小小的更新,如果我注释掉post函数中的SignUpDate,LastLogin变量,我在MongoDBcompass中得到“object,object”,并且该对象是可折叠的,它将值保存在数据库中,但是崩溃了应用程序。必要的改变只是
SignUpDate: { type: { type: Date, default: Date.now } },
LastLogin: { type: { type: Date, default: Date.now } },
至
SignUpDate: {
type: Date, default: Date.now(),
},
LastLogin: {
type: Date, default: Date.now(),
}
这就是它在数据库中的样子,它被保存并且应用程序不会崩溃。但是当我在route函数中取消注释“signupdate”时,我再次得到相同的未定义错误。
我可以接受,但我宁愿不接受。此外,如何将“type:Date,default:Date.now()”转换为“Sun May 10 2015 19:50:08 GMT-0600(MDT)”这样的好输出呢?如果我在模式中更改它,它不会起作用;如果我在route函数中更改它,它不会让我链接函数,并且我不知道在哪里声明好格式输出的var。
删除“SignUpdate”:
const user = new User({
username,
email,
password: hasdPsw,
loggedin: true
});
如果指定了默认值,则在创建新对象时不需要指定它。如果想要累积不成功的尝试次数,就需要从基数中获取用户,将计数器增加一并在基数中更新。像这样的Smth:
let userAttempts = await User.findOne({ username });
await User.update({ username }, { $set: { attempts: userAttempts.attempts + 1 } });