Mongoose - 更新数组中的项目但无法正确过滤

Mongoose - update an item inside an array but unable to filter correctly

我目前正在尝试更新包含数组的文档。该数组由几个项目组成。我的更新过滤器为 productConfiguration.id 然后更新。但是,我没有得到任何更新。我尝试了多种不同的方法,但没有运气。正确的方法是什么?

要更新的数据库条目:

{
    "id": "123",
    "name": "Test",
    "email": "test@gmail.com",
    "productConfiguration": [{
        "id": "1j6h591kz6wkznti5ta",
        "name": "tester1",
        "createdAt": {
            "$date": "2022-02-15T07:42:38.492Z"
        },
        "updatedAt": {
            "$date": "2022-02-15T07:42:38.492Z"
        }
    }, {
        "id": "1j6h591kzepkzntqins",
        "name": "tester1",
        "createdAt": {
            "$date": "2022-02-15T07:42:38.492Z"
        },
        "updatedAt": {
            "$date": "2022-02-15T07:42:38.492Z"
        }
    }],
    "__v": 0
}

猫鼬更新

app.put('/product', (req, res) => {
    MySchema.findOneAndUpdate({
        "productConfiguration.$.id" : req.body.id
    }, {
        $set: {
            "productConfiguration.$.updatedAt": req.body.updatedAt
        }
    }, {
        runValidators: true
    }, function (err, user) {
        if (!err) {
            console.log('success', 'Config update successfully!');
            res.redirect('/');
        } else {
            console.log('Error during record update : ' + err);
        }
    });
});

您的过滤器不正确,因为您在那里使用了位置运算符。您可以简单地使用 dot-notation 找到正确的 productConfiguration 元素:

MySchema.findOneAndUpdate({
        "productConfiguration.id" : req.body.id
    }, {
        $set: {
            "productConfiguration.$.updatedAt": req.body.updatedAt
        }
    }