如何在Mongodb(猫鼬)中加入模型并表达?



>我有3个模型'用户','医生','预约',我想让用户预约,然后当他得到预约时,我想返回医生姓名,当医生得到预约时,我想不返回用户名。

用户型号 :

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方法中,路径参数是您尝试检索的模型中属性的名称,因此您应该使用'_doctorID'而不是path: 'doctor',因为您在约会模型中将其用作属性名称。 这同样适用于您在.find中的查询,您正在查询 'user'属性,但您在约会模型中_userID

因此,您必须有2个选项:

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

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

最新更新