Mongo DB设置不起作用

时间:2018-04-23 14:00:41

标签: javascript mongodb mongoose

我正在尝试使用mongodb和mongoose更新数据库中的用户对象。这是架构:

const userSchema = new schema({
    username: String,
    password: String,
    firstName: String,
    lastName: String,
    age: Number,
    ticketsPurchased: [{name: String, date: Date, link: String}],
    admin: Boolean,
    billingAddress: String,
    cityResiding: String,
    stateResiding: String,
    creditCard: String,
});

这是我的代码试图更新它:

socket.on("changeUserInfo", function(data){
    console.log("CHANING USER INFO");
    console.log(data);

    User.update({username: data.username}, {
        $set: {
            firstName: data.firstname,
            lastName: data.lastName,
            billingAddress: data.billingAddress,
            creditCard: data.creditCard,
            stateResiding: data.stateResiding
        }
    });

    User.find({username: data.username}, function(err, user){
        if (err) console.log(err);
        else {
            console.log("USER = " + user);
        }
    });
});

数据是正确的,它输出正确,但是当我在User.find中输出用户时,它仍然没有更新。

2 个答案:

答案 0 :(得分:0)

数据库操作是异步的 - 您需要提供回调函数或等待Promise被解析以确保操作的顺序。

在您的情况下,find()方法很可能会在update()操作完成之前返回数据。

以下是如何实现您想要的内容 - 显示更新后的用户:

User.update(
  { username: data.username },
  {
    $set: {
      firstName: data.firstname,
      lastName: data.lastName,
      billingAddress: data.billingAddress,
      creditCard: data.creditCard,
      stateResiding: data.stateResiding
    }
  }
)
  .exec()
  .then(() => {
    // you can now be sure that the update has already completed
    User.find({ username: data.username }, function(err, user) {
      if (err) console.log(err);
      else {
        console.log("USER = " + user);
      }
    });
  })
  .catch(error => {
    // do not forget to handle errors
  });

答案 1 :(得分:0)

试试这个: 使用'findOneAndUpdate()'的'{new:true}'。这将在更改完成后向您发送数据。希望这有帮助!

    User.findOneAndUpdate({username:data.username},{$set:
    {
     firstName: data.firstname,
      lastName: data.lastName,
      billingAddress: data.billingAddress,
      creditCard: data.creditCard,
      stateResiding: data.stateResiding
    }
    }, {new:true},
    (err,docs)=>{
    //do something here
    }
    )