79217981

Date: 2024-11-23 14:06:04
Score: 0.5
Natty:
Report link

Following @jQueeny's explanation, I implemented the following (posted in case useful for others):

const estate = await db.collection('estates').findOne({ name: req.params.estateName });
if (!estate) {
  return res.status(404).json({ error: 'Estate not found' });
}

// Check asset of this name does not already exist
if (estate[assetType] && estate[assetType].find (el => el.name === req.body.name)) {
  return res.status(409)
    .json({ error: `An entry with name ${req.body.name} already exists in ${assetType}` });
}

let insertObj = {};
insertObj[assetType] = req.body;

const result = await db.collection('estates').updateOne(
  { name: req.params.estateName },
  { $push: insertObj }
);
if (result.matchedCount === 0) {
  return res.status(404).json({ error: 'Estate not found' });
}
res.status(201).json(req.body);
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @jQueeny's
  • Self-answer (0.5):
Posted by: minisaurus