Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

129
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda