[英]Mongo DB set not working
I'm trying to update a user object in my database using mongodb and mongoose. 我正在尝试使用mongodb和mongoose更新数据库中的用户对象。 Here's the schema: 这是模式:
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,
});
Here's my code trying to update it: 这是我的代码尝试对其进行更新:
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);
}
});
});
The data is correct, it outputs correctly but when I output user in the User.find it remains un-updated. 数据是正确的,它可以正确输出,但是当我在User.find中输出user时,它仍然未更新。
Database operations are asynchronous - you need to provide a callback function or wait a Promise to be resolved in order to be sure about the order of operations. 数据库操作是异步的-您需要提供一个回调函数或等待Promise被解决才能确定操作的顺序。
In your case the find()
method will most likely return the data before the update()
operation has finished. 在您的情况下, find()
方法很可能在update()
操作完成之前返回数据。
Here is how to acheive what you want - display the updated user: 这是实现所需内容的方法-显示更新的用户:
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
});
Try this: Use the '{new:true}' of the 'findOneAndUpdate()'. 尝试以下操作:使用'findOneAndUpdate()'的'{new:true}'。 This will send you the data after changes have been made. 进行更改后,这将向您发送数据。 Hope this helps! 希望这可以帮助!
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
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.