I want to update an array within a document, only if the object being pushed to the "items" array has a unique id within the "items" array.
{
"_id": "6039e37cb6b60f4694a16705",
"list_name": "Example Picklist",
"author_id": "6027f627141a75567cc2e0b0",
"author_name": "Test",
"items": [
{
"upcs": [
"111222333"
],
"qty": 10,
"id": "123456",
"name": "Item A"
},
{
"upcs": [
"444555666"
],
"qty": 22,
"name": "Item B",
"id": "987654"
}
],
"status": "initialized",
"__v": 0
}
For example, I should be able to add:
{
"name": "Item C",
"qty": 99,
"upcs": ["111555999"],
"id": "111111"
}
but not:
{
"name": "Item C",
"qty": 99,
"upcs": ["111555999"],
"id": "123456"
}
My put request is currently not refusing req.bodys with already existing ids, after I tried implementing JohnnyHK's answer to this question.
router.put('/:id', auth, async (req, res) => {
const item = req.body; // insert above examples
try {
let picklist = await Picklist.findById(req.params.id);
if (!picklist)
return res.status(404).json({ json: 'Picklist not found' });
picklist = await Picklist.findByIdAndUpdate(
{ _id: req.params.id, 'items.id': { $ne: item.id } },
{
$push: { items: item },
},
{ new: true }
);
res.json(picklist);
} catch (err) {
console.error(err.message);
res.status(500).json({ msg: 'Server Error' });
}
});
What am I getting wrong? At the moment it will push anything that fits with the Schema, and doesn't stop ID duplicates.