I am currently trying to update a document that has an array. The array is composed of a couple of items. My update filters for the productConfiguration.id
and then updates. However, I am not getting any update. I have tried multiple different ways and no luck. What is the right approach for this?
DB Entry to update:
{
"id": "123",
"name": "Test",
"email": "[email protected]",
"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
}
Mongoose update
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);
}
});
});
CodePudding user response:
Your filter is not correct as you're using the positional operator there. You can simply use dot-notation to find the correct productConfiguration
element:
MySchema.findOneAndUpdate({
"productConfiguration.id" : req.body.id
}, {
$set: {
"productConfiguration.$.updatedAt": req.body.updatedAt
}
}