首页 > 解决方案 > 我将如何在 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"
    }
}

标签: javascriptmongodbexpressmongoose

解决方案


在这里,您可以$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
}

有关$lookup$ref的更多详细信息,请查看官方文档


推荐阅读