$ mongoDB findOneAndUpdate() 中的投影

2024-02-11

我正在尝试使用 Express 和 Mongoose 构建一个简单的任务队列。这个想法是获取单个客户端并返回活动 ID 和客户端 ID(这是活动的子文档)。每次有人获取客户端时,其状态代码都会设置为 1。我提出了以下查询:

router.post('/lease', (err, res) => {
    Campaign.findOneAndUpdate({'isEnabled': true,  'clients.contact_status_code': 0}, {
            '$set': { 'clients.$.contact_status_code': 1 },
        },
        {
            new: true,
            projection: {
                'clients.$': true,
            },
        },
        (err, campaign) => {
            if (err) {
                return res.send(err);
            }

            res.json(campaign);
        }
    );
});

但连接到此端点后我得到的只是:

{"_id":"591483241a84946a79626aef","clients":[{},{}]}

在我看来,问题出在 $ 投影上,但我不知道如何解决这个问题。

编辑:我尝试使用以下代码,利用 $elemMatch:

router.post('/lease', (err, res) => {
    Campaign.findOneAndUpdate({'isEnabled': true,  'clients.contact_status_code': 0}, {
            '$set': { 'clients.$.contact_status_code': 1 },
        },
        {
            new: true,
            projection: {
                clients: {
                    '$elemMatch': {contact_status_code: 1},
                }
            },
        },
        (err, campaign) => {
            if (err) {
                return res.send(err);
            }

            res.json(campaign);
        }
    );
});

不幸的是,每个请求都会生成集合中符合条件的第一个子文档,而不是特定的已更新的子文档。这是一个例子:

假设我在 mongo 中有以下文档:

    {
    "_id" : ObjectId("591493d95d48e2738b0d4317"),
    "name" : "asd",
    "template" : "{{displayname}}",
    "isEnabled" : true,
    "clients" : [
            {
                    "displayname" : "test",
                    "_id" : ObjectId("591493d95d48e2738b0d4319"),
                    "contact_status_code" : 0
            },
            {
                    "displayname" : "client",
                    "_id" : ObjectId("591493d95d48e2738b0d4318"),
                    "contact_status_code" : 0
            }
    ],
    "__v" : 0

}

我第一次运行查询并得到以下结果:

{"_id":"591493d95d48e2738b0d4317","clients":[{"displayname":"test","_id":"591493d95d48e2738b0d4319","contact_status_code":1}]}

注意客户端 ID“591493d95d48e2738b0d4319”——这次它按预期运行。但是当我第二次运行相同的查询时,我得到了完全相同的对象,尽管我希望得到一个 ID 为“591493d95d48e2738b0d4318”的对象。


问题在于new: true

这是一个工作示例:

Campaign.findOneAndUpdate({'isEnabled': true,  'clients.contact_status_code': 0}, {
            '$set': { 'clients.$.contact_status_code': 1 },
        },
        {
            //new: true <-- this was causing the trouble
            projection: {
                clients: {
                    '$elemMatch': {contact_status_code: 0}, // 0 because the old record gets matched
                },
            },
        },
        (err, campaign) => {
            if (err) {
                return res.send(err);
            }

            res.json(campaign);
        }
    );

我假设,当new:true设置后,mongo 会丢失匹配的上下文。不幸的是,这种方法返回旧记录,但这仍然满足我获取 _id 的需要。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

$ mongoDB findOneAndUpdate() 中的投影 的相关文章

随机推荐