【发布时间】:2018-06-12 02:16:26
【问题描述】:
如何根据一些属性值访问嵌套在对象数组中的单个对象,该对象数组嵌套在另一个对象数组中,类似于伪代码中的内容:
选择 DAY=1 WHERE _id=5a3469f22dc3784bdd9a6190 AND MONTH=12
Mongoose 模型架构如下所示。根据需要,子文档的列表高于其对应的父文档,dailySchedulesSchema 最高:
var dailySchedulesSchema = new mongoose.Schema({
day: Number,
dayStart: Number,
firstBreakStart: Number,
firstBreakEnd: Number,
lunchStart: Number,
lunchEnd: Number,
secondBreakStart: Number,
secondBreakEnd: Number,
dayEnd: Number,
workDuration: Number
});
var monthlyScheduleSchema = new mongoose.Schema({
month: {type: Number, required: true },
dailySchedules: [dailySchedulesSchema]
});
var employeeSchema = new mongoose.Schema({
name: {type: String, required: true},
surname: {type: String, required: true},
email: {type: String, required: true},
phone: {type: String, required: true},
occupation: {type: String, required: true},
status: {type: Boolean, required: true},
monthlySchedule: [monthlyScheduleSchema]
});
这是我正在尝试处理的数据库中的员工条目。:
"_id" : ObjectId("5a3469f22dc3784bdd9a6190"),
"name" : "Eric",
"surname" : "K. Farrell",
"email" : "EricKFarrell@dayrep.com",
"phone" : "864-506-7281",
"occupation" : "Employee",
"status" : true,
"monthlySchedule" : [
{
"month" : 12,
"dailySchedules" : [
{
"day" : 1,
"dayStart" : 480,
"firstBreakStart" : 600,
"firstBreakEnd" : 615,
"lunchStart" : 720,
"lunchEnd" : 750,
"secondBreakStart" : 870,
"secondBreakEnd" : 885,
"dayEnd" : 1020,
"workDuration" : 480
},
{
"day" : 2,
"dayStart" : 540,
"firstBreakStart" : 630,
"firstBreakEnd" : 645,
"lunchStart" : 750,
"lunchEnd" : 780,
"secondBreakStart" : 870,
"secondBreakEnd" : 885,
"dayEnd" : 1050,
"workDuration" : 480
}
]
}
]
}
获取单日的路线本身是:"/employees/:employeeid/:month/:day"。
虽然我设法访问了父文档(例如列出所有员工),但我无法列出特定的子文档条目(例如该员工的具体日程安排) - mongoose 要么已返回当月的所有现有日程安排或者什么都没有:
(...)
var sendJsonResponse = function(res, status, content){
res.status(status);
res.json(content);
}
(...)
module.exports.empDayReadOne = function(req, res){
var monthParam = req.params.month;
var employeeid = req.params.employeeid;
var dayParam = req.params.day;
Emp
.aggregate([
{$match: {$and: [{'monthlySchedule': {$elemMatch: {$exists: true} } }, {_id: employeeid }] } },
{$unwind:'$monthlySchedule'},
{$unwind:'$monthlySchedule.dailySchedules'},
{$match:{ $and:[ {'monthlySchedule.dailySchedules.day': dayParam},{'monthlySchedule.month': monthParam} ] } }
])
.exec(function(err, dailySchedule){
if(dailySchedule){
sendJsonResponse(res, 200, dailySchedule);
} else if(err){
sendJsonResponse(res, 400, err);
return;
} else {
sendJsonResponse(res, 404, {"message": "This day has no schedules added."});
return;
}
});
};
【问题讨论】:
-
你用的是哪个版本
-
我使用的是 3.2.5 版本
标签: arrays mongodb mongoose aggregation-framework javascript-objects