Schema hasn't been registered for model "products" code example
Example 1: Schema hasn't been registered for model "products"
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
//product model is not imported in orders model
const orderSchema = new Schema(
{
// _id : mongoose.Schema.Types.ObjectId,
product: {
type: mongoose.Schema.Types.ObjectId,
ref: "products",//not Product
required: [true, "product id is required"],
},
quantity: { type: Number, default: 1, min: 1 },
},
{ versionKey: false, timestamps: true }
);
module.exports = mongoose.model("orders", orderSchema);
// in Orders route, no import of product is required
const orders = require("../models/orders");
const products = require("../models/products");
orders.find()
.select("quantity product _id")
.populate({ path: 'product', model: 'products' })
.exce().then().catch()
Example 2: Schema hasn't been registered for model "products"
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const products = require("../models/products");
//products model is imported
const orderSchema = new Schema(
{
// _id : mongoose.Schema.Types.ObjectId,
product: {
type: mongoose.Schema.Types.ObjectId,
ref: products, //not "products"
required: [true, "product id is required"],
},
quantity: { type: Number, default: 1, min: 1 },
},
{ versionKey: false, timestamps: true }
);
module.exports = mongoose.model("orders", orderSchema);
// in Orders route, no import of product is required
const orders = require("../models/orders");
orders.find()
.select("quantity product _id")
.populate("product", "name price")
.exce().then().catch()