在猫鼬中更新嵌套对象

时间:2020-09-03 17:17:46

标签: node.js express 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),但是当我检查数据库时,它似乎无法正常工作。我在这里做什么错了?

1 个答案:

答案 0 :(得分:0)

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对象的特定值),三个参数是一个定义操作的options的对象(new设置为true以返回新更新的对象)。

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