【问题标题】:NodeJS/MongoDB - field is being added only once?NodeJS/MongoDB - 字段只添加一次?
【发布时间】:2017-09-27 04:12:20
【问题描述】:

我正在使用 Node (Express/Mongoose) 和 MongoDB 学习 React,现在一切似乎都按预期工作,但我遇到了一个大问题:

var userSchema = new mongoose.Schema({
  login: { type: String, required: true, unique: true },
  password: { type: String, required: true }
})

app.post('/registerUser', function (req, res) {
  res.send(req.body)

  db.on('error', console.error.bind(console, 'connection error:'))

  // save user using model
  var user = new UserModel(req.body)
  user.save()
}

每次我发布登录名和密码时,它只会保存一次,然后就结束了。

例如,如果我发送 POST 三次:

login=admin&password=admin

login=admin2&password=admin2

login=admin3&password=admin3

db.users.count() 显示1 并且只有第一个 POST (admin:admin) 在数据库中。其余的被忽略。我正在运行 console.logs 来查看问题所在,但每个 POST 的 _id 都不同,但不知何故,在第一个 POST 之后不保存。我在想save 可能有问题,也许我应该使用update 或create 之类的东西,但我看过的每个教程和文档都说要使用save。

当我删除该字段并且集合为空然后发送 POST 时,它会立即保存,然后忽略所有其他 POST(第二个、第三个等)。

我做错了什么?我想在我的收藏中拥有 1 个以上的用户 :(

[编辑]

看起来我的 ID 是“即时”创建的,所以 MongoDB 应该根据文档触发 insert:https://docs.mongodb.com/manual/reference/method/db.collection.save/#behavior(我也不确定它现在在做什么,因为它看起来不像update 要么 :/)

【问题讨论】:

    标签: node.js mongodb reactjs


    【解决方案1】:

    您的问题是您的集合具有阻止创建的唯一索引,因此只需删除该索引:

    db.users.dropIndex('index name here');
    

    额外建议:

    1) db.on('error' 不会捕获数据库操作错误。

    2) 始终尝试创建记录,然后响应。 如果帐户创建成功与否,必须通知用户。

    简而言之 - 检查这个:

    db.on('error', console.error.bind(console, 'connection error:'))
    
    app.post('/registerUser', (req, res) => {
      // 1. check if user account exist
      const
        query = {
          login: req.body.login
        };
      UserModel
        .findOne(query)
        .exec((error, user) => {
          if(error) {
            console.error('ERROR:', error);
            res.status(500).send({
              type: 'system',
              message: 'Cannot create user record',
              trace: error
            });
            return;
          }
    
          if(user) {
            res.status(405).send({
              type: 'not-allowed',
              message: 'User record already exists'
            });
            return;
          }
    
          // 2. create record if user account record does not exist
          UserModel.create(req.body, (error, user) => {
            if(error) {
              console.error('ERROR:', error);
              res.status(500).send({
                type: 'system',
                message: 'Cannot create user record',
                trace: error
              });
              return;
            }
            res.send(user);
         });
      });
    });
    

    【讨论】:

      【解决方案2】:

      好的,我完全忘记了我可以使用 mongo 的 CLI 调试它,从那里很容易发现问题。如果您遇到这种情况,请尝试以下步骤:

      从命令行/终端启动 mongo。

      尝试为您复制有问题的操作节点/猫鼬句柄,在我的例子中是添加新用户:

      use users db.users.save( { login: "fromCLI", password: "fromCLI" } ) db.users.save( { login: "fromCLI2", password: "fromCLI2" } )

      阅读错误信息,在我的例子中是:

      "errmsg" : "E11000 duplicate key error collection: users.users index: username_1 dup key: { : null }"

      我没有username 索引。我曾经有。不得不放弃收藏,然后它神奇地开始工作!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-15
        • 2018-10-09
        相关资源
        最近更新 更多