![](/img/trans.png)
[英]How can I return all the subdocuments for an array of objects in Mongoose?
[英]How to return all subdocuments with Mongoose
我正在使用貓鼬並希望訪問子文檔中的所有子文檔。 總之,我想返回存儲在存儲在診所文件牙醫子文檔的所有子文檔預訂。
現在我的解決方案包含很多循環,但必須有更好的方法。 下面的代碼有效並描述了我的抱負。 如果需要,我願意重新安排架構結構。 請幫助我改進它。
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 },
});
我猜集合Clinic
的結構看起來像這樣
[
{
_id: ObjectId('5fa36e4d0e5796a0221bad0d'),
dentists: [
{schedule: [{booking: {reserved: true, foo: 'bar1'}}]},
{
schedule: [
{booking: {reserved: false, foo: 'bar2'}},
{booking: {reserved: true, foo: 'bar3'}}
]
}
]
},
{
_id: ObjectId('5fa373340e5796a0221bad0e'),
dentists: [
{schedule: [{booking: {reserved: true, foo: 'bar4'}}]},
{schedule: [{booking: {reserved: false, foo: 'bar5'}}]}
]
}
]
如果結構正確,則可以運行聚合
Clinic.aggregate(
[
{
$project: {
_id: 0,
temp: '$dentists.schedule.booking'
}
},
{
$unwind: {
path: '$temp'
}
},
{
$unwind: {
path: '$temp'
}
},
{
$match: {
'temp.reserved': true
}
},
{
$group: {
_id: null,
available_times: {
$addToSet: '$temp'
}
}
}
]
)
你可以得到這樣的結果
{
_id: null,
available_times: [
{reserved: true, foo: "bar4"},
{reserved: true, foo: "bar3"},
{reserved: true, foo: "bar1"}
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.