javascript - 我将如何在 Mongoose 和 Express 中引用我的问题模型
问题描述
我想引用调查模型中引用的我的问题模型文本。我能够获得问题的 ID,但如果我写,我无法获得 QuestionText
SurveyList[count].Questions.QuestionText
这有效:
SurveyList[count].Questions._id
前端的完整代码:
<!-- All Surveys -->
<% for (let count = 0; count < SurveyList.length; count++) { %>
<tr>
<!-- Display title -->
<td class="text-center text-white"><%= SurveyList[count].Title %></td>
<!-- Display type -->
<td class="text-center text-white"><%= SurveyList[count].Type %></td>
<td class="text-center text-white"><%= SurveyList[count].Questions._id %></td>
<% } %>
我的问题模型架构:
// create a question model
let questionModel = mongoose.Schema(
{
QuestionText: String,
Options: String,
},
{
collection: "questions",
}
);
我的调查模型架构:
let surveyModel = mongoose.Schema(
{
Title: String,
Type: [String],
Questions: { type: mongoose.Schema.Types.ObjectId, ref: "questions" },
Answered: { type: Number, default: 0 }, // how many times users answered
DateCreated: { type: Date, default: Date.now }, // date created
Lifetime: { type: Date, default: Date.now }, // Survey expiry
},
{
collection: "surveys",
}
);
控制器:
module.exports.displayLiveSurveys = (req, res, next) => {
Survey.find((err, surveyList) => {
if (err) {
return console.error(err);
} else {
res.render("content/survey/live-surveys", {
title: "Live Surveys",
page: "live-surveys",
username: req.user ? req.user.username : "",
SurveyList: surveyList,
});
}
});
};
如果有一种方法可以在 Survey.find 中引用 Question.find 并将 QuestionList 添加到 res.render 也可能有效?我试过了,但没有运气。
调查有效载荷:
{
"_id": {
"$oid": "60fd0c7ecd479a846f1f0fe5"
},
"Type": ["TF"],
"Answered": {
"$numberInt": "0"
},
"Title": "hello",
"Questions": {
"$oid": "60fd067d736566143839e3fd"
},
"DateCreated": {
"$date": {
"$numberLong": "1627195005136"
}
},
"Lifetime": {
"$date": {
"$numberLong": "1627195005136"
}
},
"__v": {
"$numberInt": "0"
}
}
问题有效载荷:
{
"_id": {
"$oid": "60fd0cbacd479a846f1f0fe6"
},
"QuestionText": "test",
"Options": "tester",
"__v": {
"$numberInt": "0"
}
}
解决方案
在这里,您可以$lookup
像使用手动引用一样简单地连接两个集合的文档。
查询将如下所示:
db.survey.aggregate([
{
"$match": {
_id: ObjectId("60fd0c7ecd479a846f1f0fe5")
}
},
{
$lookup: {
from: "question",
localField: "Questions",
foreignField: "_id",
as: "Questions"
}
}
])
这是测试用例的游乐场链接:Mongo Playground
或者
您可以使用 DBRefs,您的驱动程序将自动解析引用,因为您的调查文档将如下所示
{
"_id": ObjectId("60fd0c7ecd479a846f1f0fe5"),
"Type": ["TF"],
"Answered": 0,
"Title": "hello",
"Questions": {
// this is DBRef
"$ref" : "question",
"$id" : ObjectId("60fd0cbacd479a846f1f0fe6"),
"$db" : "sample"
},
"DateCreated": 1627195005136,
"Lifetime": 1627195005136,
"__v": 0
}
推荐阅读
- r - R:函数在内部 IF 语句后停止
- c# - Xamarin.Android 和 RecordAudio:如何结合文件写入和其他任务
- javascript - 如果我不存储 Array.map 的返回值会怎样?
- html - 如何使滑块箭头更高
- javascript - 在 Javascript 中插入字符串 - 法语键盘
- vb.net - 使用 VB.Net 创建 MS Access 数据库文件、表和字段
- sql - 有没有办法增加 tfs 2013 中的数据库大小限制我的收藏已满?
- android - 无限制地触发 JobService
- python - 用于多行字符串连接的 Python 循环
- reactjs - 如何部署使用 API-server 的 react 应用程序?