gpt4 book ai didi

javascript - 编辑以前保存的文档也会在数据库中更新它

转载 作者:行者123 更新时间:2023-12-03 07:15:52 24 4
gpt4 key购买 nike

仅供引用,在 Node.js 上使用 Mongodb、Express 和 Mongoose。

我正在使用 .save() 保存文档(一个包含数据的用户),然后我想通过 .send() 在请求中返回该用户。但是我当然不想返回其密码,因此我正在访问以前保存的文档并使用以下命令删除密码:

user.status = /* Create new status and assign */;
user.save();
user.password = undefined;

应该注意的是,这是在几个回调中(伪代码):

Users.findOne (
// Do stuff
user.token = /* New token */;
user.save();

Shops.findOne( /* search by userId */
// Do stuff
user._shopId = shopId;
user.status = "active";
user.save();

// Hide password
user.password = undefined;

// Send
res.send({success: true, user: user});
)
)

我希望该用户的数据库文档保持不变,因为我在编辑后没有保存它。是的,如果我不 .save(),我可以随意更改它(例如使用更新来更新它及其回调.send()) .

但是,文档的密码被删除。 .save() 是否以某种方式异步,或者仅在线程生命周期结束时运行,即使我将其放在代码中间?

谢谢。

最佳答案

user.save();提供回调。像这样的事情:

Users.findOne (
// Do stuff
user.token = /* New token */;
user.save();

Shops.findOne( /* search by userId */
// Do stuff
user._shopId = shopId;
user.status = "active";
user.save(function(err, user){
if(err) console.log(err);
if(user){
// Hide password
user.password = undefined;
res.send({success: true, user: user});
}
});
));

回调中的所有内容都将是同步的。因此只有当用户被保存时才会发送响应。

需要注意的是,.save()使用对象的指针来保存,并没有通过参数静态发送对象,因此在.save()之前更改此对象 Finishes 意味着在保存到数据库之前它将被更改。

关于javascript - 编辑以前保存的文档也会在数据库中更新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36431737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com