我有一个用于登录目的的数据库,其中包含loginidusernamepassword等。如何定义我的usernamesloginidspasswords在MongoDB中是唯一的?这意味着不允许创建任何重复项。这是我使用的一些代码:

app.post('/api/register', async function (req, res){
  try  {
    const hashedPassword = await bcrypt.hash(req.body.password, 10);
    console.log(hashedPassword);
    console.log(await bcrypt.compare('testtest',hashedPassword));
    var user = new User({ loginId: req.body.id, firstname: req.body.username, password: hashedPassword });
    user.save(function (err, User) {
      if (err) return console.error(err);
      console.log("Saved successfully");
    });
    jwt2.sign({user}, 'secrethere', { expiresIn: '15min'}, (err, token) =>{
    res.json({
      token
    });
  });
  } catch (err) {
    res.status(500).send()
    console.log(err);
  }
});


我的user.js:

const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
    loginId: String,
    firstname: String,
    lastname: String,
    eMail: String,
    password: String,
    active: Boolean
});

module.exports = mongoose.model("User", userSchema);

最佳答案

您可以在猫鼬模式定义中使用unique: true选项。此选项在字段上创建unique index

使密码字段唯一可能不是一个好主意。

const mongoose = require("mongoose");

const userSchema = mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  firstname: String,
  lastname: String,
  active: Boolean
});

module.exports = mongoose.model("User", userSchema);


当尝试插入重复的loginId时,这将导致如下错误:


  UnhandledPromiseRejectionWarning:MongoError:E11000重复密钥
  错误收集:....


应该使用此unique: true选项创建唯一索引。

但是它不会创建,您可以使用以下脚本手动创建:

db.users.createIndex( { "email": 1 }, { unique: true } );
db.users.createIndex( { "username": 1 }, { unique: true } );


我还像这样重构了您的注册路线:

app.post("/api/register", async (req, res) => {
  const { username, email, password, firstname, lastname } = req.body;

  let user = new User({ username, email, password, firstname, lastname });

  try {
    user.password = await bcrypt.hash(user.password, 10);
    user = await user.save();

    const token = jwt.sign(
      {
        _id: user._id,
        username: user.username,
        email: user.email,
        firstname: user.firstname,
        lastname: user.lastname
      },
      "secrethere",
      { expiresIn: "15min" }
    );

    res.json({
      token
    });
  } catch (err) {
    console.log(err);
    res.status(500).send("Something went wrong");
  }
});

关于javascript - Mongoose 独特的 key ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59161013/

10-09 02:01