Home > other >  MissingSchemaError: Schema hasn't been registered for model "farm"
MissingSchemaError: Schema hasn't been registered for model "farm"

Time:09-16

I have a database where I have two collections : farms and products.

Farms are associated to the product and products have multiple farms where they can be found.

The below code is from products.js

const mongoose = require("mongoose");
const { Schema } = mongoose;

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
    min: 0,
  },
  category: {
    type: String,
    lowercase: true,
    enum: ["fruit", "vegetables", "dairy"],
  },
  farm: [
    {
      type: Schema.Types.ObjectId,
      ref: "farm",
    },
  ],
});

const Product = mongoose.model("Product", productSchema);

module.exports = Product;

I have a get route that takes the id from req.params and finds the product using ID as a reference which works fine. However, whenever I try to populate the product with "farm" I get the Schema hasn't been registered error. However, whenever I check the mongo collections I can see that that it is associated with the farm.

Mongo Shell

I cross checked the schema and I think I have correctly exported the schema but I keep hitting the MissingSchema Error and just can't find where the error is.

This is my code where I am hitting an error.

const mongoose = require("mongoose");
const Farm = require("./models/farm");
const Product = require("./models/products");
app.get("/products/:id", async (req, res, next) => {
  const { id } = req.params;
  const products = await Product.findById(id).populate("farm");
  console.log(products);
  res.render("product/details", { products });
});

If I exclude the populate method the product details are being show but everytime I include the populate method I get this error

UnhandledPromiseRejectionWarning: MissingSchemaError: Schema hasn't been registered for model "farm".

CodePudding user response:

When you created the FarmSchema model did you name it ‘Farm’?

const Farm = mongoose.model(‘Farm’, FarmSchema)

When you reference that model in the ProductsSchema you have called it ‘farm’, lowercase which is a different variable, it will need to be the same as the variable used to create the model.

farm: [
{
  type: Schema.Types.ObjectId,
  ref: "farm", // this should be; ref: “Farm”
},
  • Related