我是新来的.js并希望为用户创建注册和登录页面.此外,还必须为用户提供适当的授权.我想将用户信息存储在mongodb数据库中.我怎样才能做到这一点.有人能给我提供这样做的代码吗,这样我就可以开始使用node了.js和mongodb.请帮忙

推荐答案

You can find a complete sample of what you're trying to do in the Nodepad application by Alex Young. The 2 important file you should take a look at are these 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岁.

Mongodb相关问答推荐

为什么这个查询可以在MongoDB中使用?

如何填充Mongoose中的嵌套引用

Mongo按最大分组排序

数组过滤器 MongoDB

使用 mongo-driver/mongo 使用键/值对中的值表达式查找文档

Mongoose - $project 嵌套的对象数组到数组的根级别

根据聚合管道MongoDB Atlas触发器中的条件更新多个字段

MongoDB 将 JSON 字符串转换为数组[{obj1},{obj2}]的实际对象

如何将以下聚合查询转换为 bson 并在 golang 中执行

有没有办法在 Prisma for MongoDB 的模式中显式声明 int32?

在 MongoDB 中,如何使用对当前值进行操作的函数来更新嵌套文档的值?

Mongo:投影不影响布尔值

MongoDB:使用数组过滤器进行更新插入

使用模拟 MongoDB 服务器进行单元测试

如何使用sailsjs v0.10连接mongodb?

MongoDB $或PHP中的查询

使用 MongoDB 更新数组字段内的特定键/值

MongoDB 中的多个 $inc 更新

更新时提示Field name duplication not allowed with modifiers

MongoDB 引用的最佳实践