【发布时间】:2021-02-17 18:15:28
【问题描述】:
我正在使用 mongoose 并希望访问子文档中的所有子文档。简而言之,我想返回存储在 clinic 文档中的 dentist 子文档中的所有 booking 子文档。
现在我的解决方案包含很多循环,但必须有更好的方法。下面的代码有效并描述了我的野心。如果需要,我愿意重新安排架构结构。请帮助我改进它。
router.post('/available-times', function (req, res) {
let available_times = [];
Clinic.find()
.then((clinics)=> {
clinics.forEach((clinic) => {
clinic.dentists.forEach((dentist) => {
dentist.schedule.forEach((booking) => {
if(!booking.reserved){
available_times.push(booking)
}
})
})
});
const response = {
success: true,
result: available_times,
}
res.json(response)
})
.catch(err => res.status(400).json("Error: " + err));
})
诊所架构:
const clinicSchema = new Schema({
address: { type: String},
clinic_name: { type: String},
contact_person: { type: String},
dentists: [Dentist.schema],
description: { type: String},
email: { type: String},
isVerified: { type: Boolean, default: false },
location: { type: String},
logo_url: { type: String},
});
牙医架构:
const dentistSchema = new Schema({
biography: { type: String},
languages_spoken: [String],
name: { type: String},
offered_services: [String],
picture_url: { type: String},
reviews: { type: Array},
schedule: [Booking.schema],
});
预订架构:
const bookingSchema = new Schema({
title: { type: String},
start: { type: Date},
end: { type: Date},
customer_email: { type: String},
customer_name: { type: String},
customer_phone: { type: String},
dentist_id: { type: String},
dentist_name: { type: String},
clinic_id: { type: String},
price: { type: Number},
reserved: { type: Boolean, default: false },
});
【问题讨论】:
-
虽然所有信息都在帖子中。示例文档或指向它的链接会有所帮助
-
我现在添加了示例文档
标签: node.js mongodb mongoose mongodb-query mongoose-schema