【问题标题】:How to Join model in Mongodb(Mongoose) and express?如何在Mongodb(Mongoose)中加入模型并表达?
【发布时间】:2022-02-17 00:50:08
【问题描述】:

我有3个模型'User','Doctor','Appointment',我想让用户预约然后当他预约时我想返回医生姓名,当医生预约时我想要返回用户名。

用户模型:

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 };

博士模型:

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 };

约会模式:

 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 };

进行预约:

   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}`,
    });
}
 });

我的问题是如何返回与用户名相同的医生姓名??

【问题讨论】:

  • 什么不起作用?你在正确的道路上,你需要使用populate,但根据the docs,你只需要给他你想要填充的密钥。您还可以填充多个字段:.populate('doctor', 'user');
  • 您是否还想在创建新约会时填充任何字段?
  • 我只想填充用户名和医生姓名

标签: node.js express mongoose


【解决方案1】:

.populate 方法中,路径参数是您尝试检索的模型中属性的名称,因此您应该使用path: 'doctor' 而不是'_doctorID',因为您使用它作为约会模型中的属性名称。 .find 中的查询同样适用,您正在查询 'user' 属性,但您的约会模型中有 _userID

所以,你有两个选择:

  1. _userID_doctorID改成userdoctor,这样应该会更好;
  2. 或将控制器中的userdoctor 更改为_userID_doctorID

如果您遵循第一个选项,您的代码现在应该是这样的:

约会模式:

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 };

约会控制器:

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}`,
        });
    }
});

【讨论】:

    【解决方案2】:

    如果你想选择特定的列。 它看起来像 .populate('author', 'name'). // only return the Author name

    【讨论】:

      猜你喜欢
      • 2021-06-18
      • 2018-11-05
      • 2017-06-02
      • 1970-01-01
      • 2021-07-08
      • 2019-03-15
      • 2016-09-14
      • 2018-07-10
      • 1970-01-01
      相关资源
      最近更新 更多