繁体   English   中英

更新 Mongoose 中的嵌套对象

[英]Updating a nested objects in Mongoose

我有以下快速路线:

const updateSnapshot = async (req, res) => {
    const accountId = req.body.account_id;

    if (!accountId) {
        return fail(res, 'account id is missing', 400);
    }

    try {
        const account = await Account
            .findOne({ _id: accountId})
            .populate({
                path: 'snapshot',
                model: 'Snapshot'
            });
        // I want to update these fields in snapshot
        const snapshot = {
          friends_count: data.friends_count,
          updated_date: new Date() 
        };


       account.snapshot.friends_count = snapshot.friends_count;
       account.snapshot.updated_date = snapshot.updated_date;

       await account.save();

      return success(res, snapshot);
    } catch(error) {
        fail(res, error.message, 500);
    }
};

我想更新嵌套对象snapshot (只是字段friends_countupdate_date )但是当我检查数据库时它似乎不起作用。 我在这里做错了什么?

const updateSnapshot = (req, res) => {
    const accountId = req.body.account_id;

    if (!accountId) {
        return fail(res, 'account id is missing', 400);
    };

    Account
        .findOneAndUpdate({ _id: accountId }, {
            $set: {
                snapshot: {
                    friends_count: data.friends_count,
                    updated_date: new Date()
                }
            }
        }, {
            new: true
        })
        .then(account => {
            if(!account) {
                return fail(res, "Account not found", 404);
            } else {
                return success(res, account);
            };
        })
        .catch(err => {
            return fail(res, error.message, 500);
        });
};

这里我们使用findOneAndUpdate方法并承诺在一次操作中查找和更新文档。

findOneAndUpdate将查询条件作为第一个参数,第二个参数更新对象中指定的值(我们使用$set操作符更新snapshot对象的特定值),第三个参数是一个对象,定义了操作的optionsnew设置为 true 以返回新更新的对象)。

注意:$set 将替换整个快照对象,因此如果快照对象中有其他属性,则需要将它们包含在$set对象中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM