首页 > 解决方案 > 当数据在对象数组中时,使用 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. 请帮助不知道该怎么做。

标签: node.jsmongodbexpressmongoose

解决方案


我在另一篇 SO 帖子中找到的一个简单解决方案是这样的:

const result = await timesheetModel.findOne(query).populate({
     path: 'data.project data.activity data.task'
});

推荐阅读