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

Editing a previously saved document also updates it in the db

本文关键字:文档 更新 数据库 保存 编辑      更新时间:2024-01-02

FYI,在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()完成之前更改此对象意味着它将在保存到数据库之前进行更改。