0

我正在尝试在一个属性中引用两个文档,我一直在检查官方文档,但我没有得到解决方案...

目前我正在尝试这个......

items: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: ['items','users']
}],

他们在文档中提到了 refPath ......但我无法填充这两个模型......有什么解决方案吗?

// 文档链接 https://mongoosejs.com/docs/populate.html#dynamic-ref

4

1 回答 1

0

您不需要在数组中传递 refs。这是简单的解决方案:

Mongoose 模型 (Report.js): 您可以清楚地看到我没有将任何ref传递给我的模型,但您仍然可以在 post/get API 中使用多个 ref。接下来我将向您展示。

const mongoose = require('mongoose');

const reportSchema = new mongoose.Schema({
    reportFrom : {
        type: mongoose.Schema.Types.ObjectId,
        require: true,
    },
    reportTo: {
        type: mongoose.Schema.Types.ObjectId,
        require: true,
    },
}
);

module.exports = mongoose.model("report", reportSchema);

上面的“ reportTo ”是指用户要举报的某个帖子的ID或用户要举报的用户个人资料的ID。表示“ reportTo ”可能是 User Profile 或 Post 的 ID。因此,如果“ reportTo ”包含用户 ID,那么我必须参考用户集合,但如果“ reportTo ”包含帖子 ID,那么我必须参考帖子集合。那么,我如何使用两个参考。我将简单地从邮递员传递类型查询来告诉哪个参考去帖子或用户。请参阅下面我的 API 请求:

API 文件 (reports.js)

const reports = req.query.type === "Post" ? await Report.find({reportTo: req.params.id}).populate({
                path: 'reportFrom', // attribute name of Model
                model: "User", // name of model from where you want to populate
                select: "name profilePicture", // get only user name & profilePicture
            }).populate({
                path: 'reportTo', // attribute name of Model
                model: "Post",
            }).sort({ _id: -1 })

            : req.query.type === "Profile" ? await Report.find({reportTo: req.params.id}).populate({
                path: 'reportFrom', // attribute name of Model
                model: "User",
                select: "name profilePicture",
            }).populate({
                path: 'reportTo', // attribute name of Model
                model: "User",
                select: "name profilePicture",
            })
            .sort({ _id: -1 })
            : null 

            return res.status(200).json(reports);

请参阅第 7 行和第 15 行,您可以清楚地看到我如何为同一属性使用两个不同的参考。在第一种情况下,reportTo 指的是Post模型,而在第二种情况下, reportTo是指用户模型。

于 2022-01-06T07:33:03.313 回答