Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
Creating new mongoose sub-doc and appending to existing parent doc

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 })
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Nevermind! I realised that "category" was still an array, rather than an element of the categories array as I'd assumed.

So I replaced that section with this, and now... it works!

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

    categories.forEach((category) => {
      event.categories.push(category._id);
    });

    event.save((err) => {
      if (err) return res.status(400).send(err);
    });
  });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!