Hello,
I am trying to use Mongoose populate function to get the data from another collection, but what ever I do it returns null in the returned document. I dropped both collections and some of the forums suggested, but still no luck. This is the first time I am using this feature, I am pretty sure there is something I am messing.
First Schema:
const mongoose = require("mongoose");
const RiskCatalogSchema = mongoose.Schema({
RiskId: {
type: String,
required: true,
unique: true
},
RiskGrouping: {
type: String,
required: true
},
dateAdded: {
type: Date,
default: Date.now
},
Risk: {
type: String
},
CSFFunction: {
type: String
},
Description: {
type: String
}
});
module.exports = mongoose.model("riskCatalog", RiskCatalogSchema);
Second Schema:
const mongoose = require("mongoose");
const RiskSchema = mongoose.Schema({
ID: {
type: Number,
required: true,
unique: true
},
title: {
type: String,
required: true,
unique: true
},
description: {
type: String,
required: false
},
dateAdded: {
type: Date,
default: Date.now
},
riskRating: {
type: Number,
default: 1
},
riskCategory: {
type: mongoose.Schema.Types.ObjectId,
ref: "riskCatalog"
}
});
module.exports = mongoose.model("risks", RiskSchema);
Express route /Function:
riskRouter.get("/:riskId", async (req, res) => {
try {
//const risk = await Risk.findById(req.params.riskId).populate();
const risk = await Risk.findById(req.params.riskId).populate(
"riskCategory"
);
res.status(200).json(risk);
} catch (err) {
console.log("Something is Wrong, " + err);
res.status(444).send("No risk found with the given criteria!");
}
});