Home > Back-end >  Creating new mongoose sub-doc and appending to existing parent doc
Creating new mongoose sub-doc and appending to existing parent doc

Time:10-13

I'm building a website with a database using NodeJS, MongoDB, Express, Mongoose etc.

  1. I have two schema set up: Events and a sub-doc schema Categories (among others).
  2. The function pulls in array which contains the data needed to create several categories (this bit works) as well as the Event ID appended to the end.
  3. The first few bits below just grab that ID, then remove it from the array (probably a better way to do this, but again, it works).
  4. As mentioned above, the Categories then create correctly (and even do validation), which is amazing, BUT...
  5. They don't get appended to the Event doc. The doc updates the "categories" field to an applicable number of "null" values, but I cannot for the life of me get it to actually take the IDs of the newly created categories.

I nabbed (and adjusted) the below code from somewhere, so this is where I'm at...

     exports.addCategories = catchAsync(async (req, res, next) => {
       const categories = req.body;
       const length = categories.length;
       const eventID = categories[length - 1].eventId;
       categories.pop();

    Event.findOne({ _id: eventID }, (err, event) => {
      if (err) return res.status(400).send(err);
      if (!event)
        return res.status(400).send(new Error("Could not find that event"));

    Category.create(categories, (err, category) => {
      if (err) return res.status(400).send(err);

      event.categories.push(category._id);
      event.save((err) => {
        if (err) return res.status(400).send(err);

        res.status(200).json(category);
        });
      });
     });
    });

Currently the mongoose debug output is showing the following (which confirms that MOST of it is working, but the IDs just aren't being pulled correctly):

> Mongoose: events.updateOne({ _id: ObjectId("614bc221bc067e62e0790875")}, { '$push': { categories: { '$each': [ undefined ] } }, '$inc': { __v: 1 }}, { session: undefined })

Please help!

  • Related