简体   繁体   中英

How would I reference my question model in Mongoose and Express

I would like to reference my Question model text which is referenced in the Survey model. I am able to get the ID of the question but I cannot get the QuestionText if I write

SurveyList[count].Questions.QuestionText

This works:

SurveyList[count].Questions._id

Full code for front end:

<!-- 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>
<% } %>

My Question Model Schema:

// create a question model
let questionModel = mongoose.Schema(
  {
    
      QuestionText: String,
      Options: String,
   
  },
  {
    collection: "questions",
  }
);

My Survey model schema:

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",
  }
);

Controller:

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,
      });
    
    
    }
  });
};

If there is a way to reference Question.find inside Survey.find and add QuestionList to res.render that might work too? I tried that with no luck.

Survey Payload:

{
    "_id": {
        "$oid": "60fd0c7ecd479a846f1f0fe5"
    },
    "Type": ["TF"],
    "Answered": {
        "$numberInt": "0"
    },
    "Title": "hello",
    "Questions": {
        "$oid": "60fd067d736566143839e3fd"
    },
    "DateCreated": {
        "$date": {
            "$numberLong": "1627195005136"
        }
    },
    "Lifetime": {
        "$date": {
            "$numberLong": "1627195005136"
        }
    },
    "__v": {
        "$numberInt": "0"
    }
}

Question Payload:

{
    "_id": {
        "$oid": "60fd0cbacd479a846f1f0fe6"
    },
    "QuestionText": "test",
    "Options": "tester",
    "__v": {
        "$numberInt": "0"
    }
}

Here, you can use $lookup to simply join the documents of two collections as you are using manual referencing.

Query will look like this:

db.survey.aggregate([
  {
    "$match": {
      _id: ObjectId("60fd0c7ecd479a846f1f0fe5")
    }
  },
  {
    $lookup: {
      from: "question",
      localField: "Questions",
      foreignField: "_id",
      as: "Questions"
    }
  }
])

Here is the link to playground to test your use case: Mongo Playground

OR

You can use DBRefs where your driver will resolve the reference automatically in that your survey document will look like this

{
    "_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
}

For more details on $lookup and $ref do check the official documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM