哪个包更适合在实际项目中使用 mongodb 或 mongoose?

Which package is more preferable to use in a real project mongodb or mongoose?

首先,不是我要找的。

我正在向教育项目添加数据库。对于前一个,我只是用 MongoDB.MongoClient 和 got/set 查询了数据库 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(*) 函数的文件,或数十个模式。为什么答案还是不明显?

  1. Mongoose 在后台使用 mongodb 驱动程序
  2. 将 cpu/memory 繁重的任务放在客户端不是一个好的做法
  3. mongo也不 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');
  }
})