I need a little help, I’ve a category schema, which looks like below,
let mongoose = require("mongoose");
let schema = mongoose.Schema;
const _ = require("lodash");
let category = new schema(
{
// Primary Fields
categoryName: { type: String, unique: true },
isArchived: { type: Boolean, default: false },
isDeleted: { type: Boolean, default: false },
categoryImage: { type: String },
categorySlug: { type: String, unique: true },
createdBy:{
type: mongoose.Types.ObjectId,
ref: "Users",
}
},
{
timestamps: true,
}
);
let Category = mongoose.model("Categories", category);
module.exports = {
Category,
};
and I’m using this reference into another schema, which looks like below,
let mongoose = require("mongoose");
let schema = mongoose.Schema;
const { ObjectID } = require("mongodb");
let coupons = new schema({
city: {type:String},
categoryId: {
type: mongoose.Types.ObjectId,
ref: "categories",
},
offerCode: {type:String,unique:true},
couponName: {type:String,unique:true},
validFrom: {type:Date},
validTill: {type:Date},
visibility: { type:Boolean,default:false},
issuedFor: {type:String,enum:['BIKE','AUTO','DELIVERY','CHARGING']},
applicability: {type:String,enum:['1','2','3','4','5','6','7','8','9','10','0']},
bankType: {type:String},
isArchived: { type: Boolean, default: false },
isDeleted: { type: Boolean, default: false },
createdBy: {
type: mongoose.Types.ObjectId,
ref: "Users",
},
},
{
timestamps: true,
});
coupons.index( { "offerCode": 1,"couponName": 1,"validFrom": 1, "validTill":1, "categoryId":1 }, { unique: true } );
let Coupons = mongoose.model("Coupons", coupons);
module.exports = {
Coupons
};
everything looks pretty much good, I can use reference of other schema but the category schema is throwing MongooseError
whenever I’m trying to populate this from my code.
The code looks like below,
return await Coupons.find(query)
.populate('categoryId')
.skip(parseInt(skip)).select(select).limit(parseInt(limit)).sort({ createdAt: -1 })
can anyone please tell me what is wrong that leads me towards MongooseError [MissingSchemaError]: Schema hasn't been registered for model "categories".
Please help me. Thanks in advance.
2
Answers
The correct format would be:
You need to change the name of your model too:
Mongoose will look for the pularized, lowercase collection of the model name, so mongoose assumes
Category
->categories
.Then when you do the populate you can always explicitly specify the
path
andmodel
like soSee Compiling your first model and Saving refs for full explanation.
from this code
mongoose.model("Categories", category);
, you are defining this model with the name ofCategories
. so you will have to use the same name wherever you want to reference it.this below code should work for you.