我是 node.js 的新手,想为用户创建一个注册和登录页面。还必须对用户进行适当的授权。我想将用户信息存储在 mongodb 数据库中。我怎样才能实现这一点。可以有人为我提供了这样做的代码,以便我可以开始使用 node.js 和 mongodb。请帮助
最佳答案
您可以在 Nodepad application by Alex Young 中找到您正在尝试执行的操作的完整示例。 .您应该查看的 2 个重要文件是以下 2 个:
https://github.com/alexyoung/nodepad/blob/master/models.js
https://github.com/alexyoung/nodepad/blob/master/app.js
模型的一部分如下所示:
User = new Schema({
'email': { type: String, validate: [validatePresenceOf, 'an email is required'], index: { unique: true } },
'hashed_password': String,
'salt': String
});
User.virtual('id')
.get(function() {
return this._id.toHexString();
});
User.virtual('password')
.set(function(password) {
this._password = password;
this.salt = this.makeSalt();
this.hashed_password = this.encryptPassword(password);
})
.get(function() { return this._password; });
User.method('authenticate', function(plainText) {
return this.encryptPassword(plainText) === this.hashed_password;
});
User.method('makeSalt', function() {
return Math.round((new Date().valueOf() * Math.random())) + '';
});
User.method('encryptPassword', function(password) {
return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
});
User.pre('save', function(next) {
if (!validatePresenceOf(this.password)) {
next(new Error('Invalid password'));
} else {
next();
}
});
我想他也是explains the code on the dailyjs site .
https://stackoverflow.com/questions/8051631/
相关文章:
javascript - 在 Meteor 应用程序中实现 MongoDB 2.4 的全文搜索
ruby-on-rails - mongoid 中 embeds_many 和 has_many 的
javascript - MongoDB - 更新集合中所有记录的最快方法是什么?
mongodb - 自动重新连接异常 "master has changed"
mongodb - 只安装 mongo shell,不安装 mongodb
node.js - Node.js/Mongoose 上的 "VersionError: No ma