Mongoose Populate Function

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

This is what is returned:

{
	"_id": "62b89dc77a0a2ef69aee19cf",
	"ID": 66,
	"title": "Test Risk  3",
	"description": "Description, referncing Risk Catalog",
	"riskRating": 1,
	"riskCategory": null,
	"dateAdded": "2022-06-26T17:56:23.382Z",
	"__v": 0
}

I am also sure that the object ID exists in RiskCatalog collection.

Figured it out.

I am was using a collection with the name RiskCatalog, Apparetly mongoose creates the name and adds “s” at the end by default. so the collection name is created as RiskCatalogs instead, not sure why mongoose does that.

2 Likes

Because they decided likewise and it is documented:

https://mongoosejs.com/docs/guide.html#collection

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.