node.js - 当数据在对象数组中时,使用 mongoose.populate 和 mongoose-pagivate-v2
问题描述
我在这样的对象数组中获取一些数据:
{
"success": true,
"result": {
"docs": [
{
"_id": "60a602901a74f62935a4898f",
"user": "607030ba3c82e235443db610",
"weekNum": 19,
"__v": 0,
"createdAt": "2021-05-20T06:32:48.742Z",
"data": [
{
"activity": "6063f898232d3f2acca5d2ae",
"_id": "60a6063668f27715b0f08753",
"project": "60702d1f3c82e235443db5ff",
"task": "60702d3d3c82e235443db601",
"workingDate": "2021-05-10T18:30:00.000Z",
"dayVal": 1,
"description": ""
}
],
"managersComment": "leleleleelelel",
"status": "Submitted",
"updatedAt": "2021-05-20T06:48:22.163Z"
}
],
"paginator": {
"itemCount": 1,
"offset": 0,
"perPage": 10000,
"pageCount": 1,
"currentPage": 1,
"slNo": 1,
"hasPrevPage": false,
"hasNextPage": false,
"prev": null,
"next": null
}
}
}
我的这个集合的模式是这样的:
const timesheetSchema = new Schema({
managersComment: {
type: String
},
weekNum: {
type: Number
},
data:[{
project: {
type: Schema.ObjectId,
ref: projectModel
},
task: {
type: Schema.ObjectId,
ref: taskModel
},
activity: {
type: Schema.ObjectId,
default: null,
ref: activityModel
},
workingDate: {
type: Date
},
dayVal: {
type: Number
},
description: {
type: String
},
}],
user: { type: ObjectId, ref: userModel },
status: {
type: String,
enum: ['Saved', 'Submitted', 'Approved', 'Rejected', 'Reset']
},
}, { timestamps: true });
timesheetSchema.plugin(mongoosePaginate);
const timesheetModel = mongoose.model('timesheet', timesheetSchema);
我获取数据的代码是这样的:
try {
console.log('populateRequired --------------------------------------------------')
const populateArray = [
{ path: "task", select: "taskName" },
{ path: "project", select: "projectName" },
{ path: "activity", select: "title" },
];
const query = {
user: req.params.userId,
status: req.query.status,
};
const paginationParams = {
populate: populateArray,
customLabels: customLabels,
limit: req.query.limit,
};
console.log("USER QUERY ", query);
const userTimesheet = await getTimesheetDataByUserId(
query,
paginationParams
);
console.log(userTimesheet);
res.send({ success: true, result: userTimesheet });
} catch (err) {
console.log(err);
next(err);
}
但如上面的返回数据所示,我没有在data array
. 请帮助不知道该怎么做。
解决方案
我在另一篇 SO 帖子中找到的一个简单解决方案是这样的:
const result = await timesheetModel.findOne(query).populate({
path: 'data.project data.activity data.task'
});
推荐阅读
- sql - Oracle SQL如何将具有不同数据的行合并为单行
- sql - 旋转数据库表
- apache-spark - 用于 Spark 结构化流的 Qubole Kinesis 连接器引发错误
- linux - 是否可以控制进程的调度策略
- java - 为什么我不能通过按“输入”来打破我的 while 循环
- python - scipy ver 0.18 scipy.interpolate.UnivariateSpline 如何处理不严格增加的值?
- quarkus - 使用 Quarkus 使用 SOAP 服务
- python - 如果我的测试用例需要来自数据库而不是空数据库的数据怎么办?
- varnish - 我的清漆配置似乎无法正常工作
- ios - IOS Tabbar滚动动画:触摸指示器视图时文本改变颜色