您不需要在数组中传递 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是指用户模型。