Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda