我有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}`,
});
}
});
我的問題是如何回傳與用戶名相同的醫生姓名的預約?
uj5u.com熱心網友回復:
在該.populate方法中,路徑引數是您嘗試檢索的模型中屬性的名稱,因此path: 'doctor'您應該使用它而不是 ,'_doctorID'因為您將其用作約會模型中的屬性名稱。這同樣適用于 ' 中的查詢.find,您正在查詢 'user'屬性,但您_userID在約會模型中有。
因此,您必須有 2 個選項:
- 將
_userIDand_doctorID改為useranddoctor,這種方式應該會更好; - 或將控制器中的
userand更改為and ;doctor_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}`,
});
}
});
uj5u.com熱心網友回復:
如果要選擇特定列。它看起來像 .populate('author', 'name'). // only return the Author name
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/427374.html
