Home > Back-end >  How to Join model in Mongodb(Mongoose) and express?
How to Join model in Mongodb(Mongoose) and express?

Time:02-17

I have 3 models 'User' , 'Doctor', 'Appointment', I want to let the user make an appointment then when he get his appointment I want to return the doctor name, also when the doctor get the appointment I want t return the user Name.

User Model :

const mongoose = require('mongoose');

const User = mongoose.Schema({
name: {
    type: String,
    required: true,

},
email: {
    type: String,
    required: true,

},

password: {
    type: String,
    required: true,

},
 })

const User = mongoose.model('User', User);

 module.exports = { User };

Doctor Model :

const mongoose = require('mongoose');

const Doctor = mongoose.Schema({
name: {
    type: String,
    required: true,

},
email: {
    type: String,
    required: true,

},

password: {
    type: String,
    required: true,

 },

})

const Doctor = mongoose.model('Doctor', Doctor);

module.exports = { Doctor };

Appointment Model :

 const mongoose = require('mongoose');

 const Appointment = mongoose.Schema({
date: {
    type: Date,

},
time: {
    type: Date
},

_userID: {
    type: mongoose.Types.ObjectId,
    ref: 'User'
},

_doctorID: {
    type: mongoose.Types.ObjectId,
    ref: 'Doctor'
}
})

 const Appoitment = mongoose.model('Appoitment', Appointment);

    module.exports = { Appoitment };

Make and Get Appointment :

   const express = require('express');
   const { Appointment } = require('../DataBase/Models/appointment.model');
   const router = express.Router();



  router.get("/appointment/:id", async (req, res) => {
  try {
    const appointment = await Appointment.find({
        user: req.params.id,
    }).populate({
        path: "doctor",
        model: "Doctor",
    });
    res.send({
        status: 200,
        message: "SuccessFull",
        Appointments: appointment,
    });
} catch (error) {
    res.send({
        status: 400,
        message: `Error: ${error}`,
    });
}
});

 router.post("/appointment", async (req, res) => {

try {
    const makeAppointment = new Appointment(req.body);
    const result = await makeAppointment.save();
    res.send({
        status: 200,
        message: "SuccessFull",
        Appointment: result,
    });
} catch (error) {
    res.send({
        status: 404,
        message: `Error : ${error}`,
    });
}
 });

My Question is How I can return the Appointment with the doctor Name the same with the User Name ??

CodePudding user response:

if you want to select specific column . it will look like .populate('author', 'name'). // only return the Author name

CodePudding user response:

in the .populate method, the path param is the name of the attribute in the model that you're trying to retrieve, so instead of path: 'doctor', you should be using '_doctorID' because you used this as the attribute name in the Appointment Model. The same works for your query in the .find, you're querying the 'user' attribute, but you have _userID in your appointment model.

So, you have to 2 options:

  1. Change _userID and _doctorID to user and doctor, this way should be better;
  2. Or change user and doctor in your controller to _userID and _doctorID;

If you follow the first option, your code now should be something like:

Appointment Model:

   const mongoose = require('mongoose');
   
   const Appointment = mongoose.Schema({
      date: {
        type: Date,
    
      },
      time: {
        type: Date
      },
      user: {
        type: mongoose.Types.ObjectId,
        ref: 'User'
      },
      doctor: {
        type: mongoose.Types.ObjectId,
        ref: 'Doctor'
      }
   })
    
   const Appoitment = mongoose.model('Appoitment', Appointment);
   module.exports = { Appoitment };

Appointment Controller:

   router.get("/appointment/:id", async (req, res) => {
      try {
        const appointment = await Appointment.find({
            user: req.params.id,
        })
        .populate({
            path: "doctor",
            select: "_id name",
        });
        res.send({
            status: 200,
            message: "SuccessFull",
            Appointments: appointment,
        });
      } catch (error) {
        res.send({
            status: 400,
            message: `Error: ${error}`,
        });
      }
    });

I Hope this helps you =)

  • Related