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

185
Visualizações
mongoose get data from find method and insert them in other schema

I am trying to build a web application.

At the website, I need to get instructor data from mongodb with mongoose and some of them will be inserted in other schema(Course).

if (!req.body) return console.log("No data sent");
    var newcourse;
    var iname = req.body.iname;
    var results;


/*ilist.find({ name: iname }).toArray((err, result) => {
    if (err) return console.log(err);
    results = result;
});*/
dbs.collection('instructors').find({ name: iname }).toArray((err, result) => {
    results = result;
    //console.log(result);        
});
// console.log(ilist.data);

newcourse = new clist({
    'coursename': req.body.coursename, 'coursenumber': req.body.coursenumber, 'coursecredit': req.body.coursecredit
    , 'courseroom': req.body.room, 'instructors.name': req.body.iname, 'instructors.email': results.email, 'instructors.phone': results.phone, 'instructors.role': req.body.role
});

newcourse.save(function (err) {
    if (err) {
        console.log(err);
        res.status(400);
        res.send(err);
    }
    else {
        res.status(200);
        console.log('A new course has been registered!');
        res.redirect('/course');
    }
});

-----schema-------------------

var instructorlist = mongoose.Schema({
    name: { type: String, required: true },
    age: { type: Number, required: true },
    gender: { type: String, required: true },
    DOB: { type: Date, required: true, default: Date.now },
    email: { type: String, required: true },
    phone: { type: Number, required: true },
    address: { type: String, required: true },
    dateofstart: { type: Date, required: true},
    courses: {
        coursename: { type: String, required: false },
        coursenumber: { type: Number, requird: false },
        coursecredit: { type: Number, required: false },
        courseroom: { type: String, required: false }
    }
});
var courselist = mongoose.Schema({
    coursename: { type: String, required: true },
    coursenumber: { type: String, required: true },
    coursecredit: { type: Number, required: true },
    courseroom: { type: String, required: false },
    courseregisteddate: {type: Date, default: Date.now},
    students: {
        name: { type: String, required: false },
        phone: { type: Number, requird: false },
        email: { type: String, required: false },
        class: { type: String, required: false }
    },
    instructors: {
        name: { type: String, required: false },
        phone: { type: Number, requird: false },
        email: { type: String, required: false },
        role: { type: String, required: false }
    }
});

I want to get instuctorlist's email and phone.(others are from req.body) and put it into newcourse variable for saving in mongodb. Thank you for reading it.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The instructors find function will be called asynchronously so the javascript code will go on before you have the results of that mongoose query.

You need to add the saving of the course inside the callback. Could look like this:

if (!req.body) return console.log("No data sent");

dbs.collection('instructors').find({
  name: req.body.iname
}).toArray((err, instructors) => {
  if (!err) {
    if (!instructors) {
      var newcourse = new clist({
        // new data also from instructors
      });

      newcourse.save(function(err) {
        if (err) {
          res.status(400);
          res.send(err);
        }
        else {
          res.status(200);
          res.redirect('/course');
        }
      });
    }
    else {
      res.status(400);
      res.send("Could not find instructor");
    }
  }
  else {
    res.status(400);
    res.send(err);
  }
});

But be aware that with this you get all instructors with the given name and you have to select one from that array. If you want to save more courses to a instructor you have to change the schema: e.g.

var courseSchema = mongoose.Schema({
  // Schema variables
  ...

});

var courseModel = mongoose.model("Course", courseSchema);

var instructorlist = mongoose.Schema({
  name: {
    type: String,
    required: true
  },

  ...

  courses: [{
    type: ObjectId,
    ref: "Course"
  }]
});

over 4 years ago · Santiago Trujillo 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