In this paragraph Discous of MissingSchemaError: Schema hasn’t been registered for model products. you can check this code and solve this problem below.
Cart
const mongoose = require(‘mongoose’);
const cartSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: ‘user’, required: true },
cartItems: [
{
product : {
type :mongoose.Schema.Types.ObjectId,
ref : “product”,
required:true
},
quantity : {
type:Number,
default:1
}
}
]
} ,{timestamps:true});
module.exports = mongoose.model(‘Cart’ , cartSchema , ‘cart’);
Products
const mongoose = require(‘mongoose’);
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
slug: {
type: String,
required: true,
unique: true
},
quantity: {
type: Number,
required: true
},
price: {
type: Number,
required: true
},
description: {
type: String,
required: true,
trim: true
},
offer: { type: Number },
productPictures: [{
img: { type: String }
}],
reviews: [{
userid: { type: mongoose.Schema.Types.ObjectId, ref: “User”, review: String }
}],
category: { type: mongoose.Schema.Types.ObjectId, ref: “Categories” },
createdby: {
type: mongoose.Schema.Types.ObjectId, ref: “User”, required: true
},
updatedAT: {
type: Date
}
}, { timestamps: true });
module.exports = mongoose.model(‘Product’, productSchema);
Document
Router export method , Here is the error which is not populating the population not happening
Throws in when called from PostMan
exports.getCartItems = (req, res) => {
//const { user } = req.body.payload;
//if(user){
console.log(‘req.user._id’ , req.user._id);
Cart.findOne({ user: req.user._id })
.populate(“cartItems.product”, “_id name price productPictures”)
.exec((error, cart) => {
console.log(‘getCartItems’ , error);
if (error) return res.status(400).json({ error });
if (cart) {
let cartItems = {};
cart.cartItems.forEach((item, index) => {
cartItems[item.product._id.toString()] = {
_id: item.product._id.toString(),
name: item.product.name,
img: item.product.productPictures[0].img,
price: item.product.price,
qty: item.quantity,
};
});
res.status(200).json({ cartItems });
}
});
//}
};