在实际项目mongodb或mongoose中,哪个软件包更可取?

首先,this answer不是我想要的。

我正在为教育项目添加一个数据库。对于上一个,我刚刚使用MongoDB.MongoClient查询数据库,并使用MongoDB.MongoClient.collection.insertOne获取/设置了记录。

例如,添加用户很简单:

mongodb.MongoClient.collection("users").insertOne({
    username,password // jsut a sha512 password,which is sent hashed from UI
})

但是据我所知,正确的方法(一种更好的方法)是创建一个Mongoose Schema并为其添加功能。但是创建密码似乎比预期的要复杂得多。为什么会有区别?如果从UI窃取了密码,则使用多少次加密都无关紧要。但是,如果仅对密码进行哈希处理,则从后端窃取密码无关紧要-用已经哈希化的密码触发该端点是不可能的。

const UserSchema = new mongoose.Schema({
    username: {
        type: String,lowercase: true,unique: true,index: true,required: [true,'username can\'t be blank'],match: [/^[a-zA-Z0-9]+$/,'username is invalid'],},salt: String,hash: String,});

UserSchema.plugin(uniqueValidator,{message: 'is already taken.'});

UserSchema.methods.setPassword = function(password) {
    this.salt = crypto.randomBytes(16).toString('hex');
    this.hash = crypto.pbkdf2Sync(password,this.salt,10000,512,'sha512').toString('hex');
};

基本上,问题是: 哪种方法更好,并且暗示着我必须使用巨大的加密? 据我了解,可能只有1个具有mongodb.collection(*)函数的文件或数十个模式。为什么答案仍然不明显?

liuxueyang1119 回答:在实际项目mongodb或mongoose中,哪个软件包更可取?

  1. 在后台使用mongodb驱动程序的猫鼬
  2. 将cpu /内存繁重的任务放在客户端不是一个好习惯
  3. 不是Mongoose而非mongodb本机驱动程序,完全可以由您决定,它强制您使用任何内容,无论是否对密码进行散列(以及应如何使用重加密)。

因此,基本上,我建议您使用本机mongo驱动程序,仅使用nodejs docs中的任何简单哈希,并在创建插入之前在用户创建时添加哈希:

const hash = (password) => {
  const hash = crypto.createHash('sha256');
  hash.update(password);
  return hash.digest('hex');
}

...

app.post('/user',async (req,res) => {
  try {
    // validation of user credentials here
    const userToInsert = { ...req.body,password: hash(req.body.password) };
    await mongodb.MongoClient.collection("users").insertOne(userToInsert);
    res.status(201).send("done");
  } catch (err) {
    console.error(err);
    res.status(500).send('internal server error');
  }
})
本文链接:https://www.f2er.com/3073805.html

大家都在问