Insert an information into two Collections in Mongodb with Node.js

Asked

Viewed 66 times

3

I have two degrees: courses and participants. an attendee when enrolling in a course, when I give a GET in any course, needs to return the enrolled attendees(participants) and when giving a GET to any participant, need to return the courses enrolled (cursesInscript).

When I give a POST or PUT to the participant and/or course, the information is not saved in the fields 'participants' or 'cursosInscritos', it returns with status 200 but not saved in the database

How can I do?

cursosSchema:

const cursoSchema = new mongoose.Schema ({

    nomeCurso: {type: String, required : true },
    participantes: [{type: mongoose.Schema.Types.ObjectId, ref: 'participanteSchema', required : false}]
})

participationsSchema

const participanteSchema = new mongoose.Schema ({
    nomeCompleto: { type: String, required : true},
    cursosInscritos: [{type: mongoose.Schema.Types.ObjectId, ref: 'cursoSchema'}]
})

controller

exports.inscricaoCurso = (req, res) => {
    const {nomeCurso, local, periodo} = req.body
    const inscreverCurso = new Cursos({
        nomeCurso, local, periodo, participantes: req.params.participanteId,
    })
    inscreverCurso.save()
    try {
       Participantes.findOneAndUpdate({_id: req.params.participanteId}, {$push: {cursosInscritos: inscreverCurso._id}})
       res.status(200).send({ mensagem: "Inserido com sucesso" })

   } catch (error) {
    return res.status(500).send({ mensagem: Error })
   }
}

1 answer

1


You shouldn’t be using the async/await in his function inscricaoCurso? In his model of Participantes, it depends on the id of the model inscreverCurso which is not yet saved because it is an asynchronous operation. Therefore, Voce should hope to save the inscreverCurso Yes, when I execute the Participantes.finOneAndUpdate (depreciated) it will have the value of inscreverCurso._id.

exports.inscricaoCurso = async (req, res) => {
  const { nomeCurso } = req.body;
  const inscreverCurso = new Cursos({
    nomeCurso,
    participantes: req.params.participanteId
  });
  try {
   await inscreverCurso.save();
   await Participantes.findOneAndUpdate(
    { _id: req.params.participanteId },
    { $push: { cursosInscritos: inscreverCurso._id } }
   );
   res.status(200).json({ mensagem: "Inserido com sucesso" });
  } catch (error) {
   return res.status(500).json({ mensagem: Error });
  }
 });

I recommend you rewrite the update of Participantes in this way:

 try {
  await inscreverCurso.save();
  let participante = await Participantes.findById(req.params.participanteId);
  participante.cursosInscritos.push(inscreverCurso._id);
  await participante.save();
  res.status(200).json({ mensagem: "Inserido com sucesso" });
 } catch (error) {
  return res.status(500).json({ mensagem: Error });
 }

Try this way and do the tests.
One more thing, in the part of enrollingCurso, Voce should not check if the name of the course already exists and then only update the list of participants?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.