1

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.

Louis
  • 33
  • 6
  • I think what I might have wrong here is that `{ _id: req.params.id, 'items.id': { $ne: item.id } }` is only checking to see if the item.id doesn't exist in items, and not within each object of the items array. If this is the case, how do I tell mongoDB that I want it to search each of the unnamed objects in the items array for a matching ID? – Louis Mar 01 '21 at 16:51

1 Answers1

0

The error is that I was using

Picklist.findByIdAndUpdate()

instead of

Picklist.findOneAndUpdate()
Louis
  • 33
  • 6