NextJS & MongoDB
Unanswered
domestos posted this in #help-forum
domestosOP
While everything works fine locally in both dev and prod modes, after deploying, I get an error like:
"Schema hasn't been registered for model 'CartItem'. Use mongoose.model(name, schema)."
This happens after I add a new item to the cart. Even though the Cart and CartItem are created successfully, I'm getting an error like this.
I thought that it might be an error with the API route or fetch function, but it works because it is called after the first load of the app and does not cause an error like this.
I also thought that the populate might be causing this problem, but it seems okay, I think.
I also cleared the cache, redeployed the app, re-created models in the database, etc., but I still can't figure out where the problem is or what is causing it.
"Schema hasn't been registered for model 'CartItem'. Use mongoose.model(name, schema)."
This happens after I add a new item to the cart. Even though the Cart and CartItem are created successfully, I'm getting an error like this.
I thought that it might be an error with the API route or fetch function, but it works because it is called after the first load of the app and does not cause an error like this.
I also thought that the populate might be causing this problem, but it seems okay, I think.
I also cleared the cache, redeployed the app, re-created models in the database, etc., but I still can't figure out where the problem is or what is causing it.
2 Replies
domestosOP
part of an api route itself
cart-model
`
// Connect to the database
await connectToDb();
// Find the user's shopping cart by session identifier
let userCart = await CartModel.findOne({ sessionId });
// Check if a cart is found for the session and it's have products inside
if (!userCart || !userCart.products.length) {
return new Response(
JSON.stringify({
products: [],
cartProductsCount: 0,
totalAmount: 0,
})
);
}
await userCart.populate({
path: "products",
populate: {
path: "productItem",
model: "Product",
},
});cart-model
import mongoose, { Document, PopulatedDoc, Schema } from "mongoose";
import { ICartItem } from "./cart-item.model";
export type ICartProduct = Pick<ICartItem, "productItem">;
export interface ICart extends Document {
sessionId: string;
products: PopulatedDoc<ICartItem>[];
totalAmount: number;
}
const CartSchema: Schema = new Schema(
{
sessionId: {
type: String,
required: true,
unique: true,
},
products: [
{
type: Schema.Types.ObjectId,
ref: "CartItem",
required: true,
},
],
totalAmount: {
type: Number,
default: 0,
},
},
{ timestamps: true }
);
CartSchema.index({ updatedAt: 1 }, { expireAfterSeconds: 2592000 });
const CartModel: mongoose.Model<ICart> =
mongoose.models.Cart || mongoose.model<ICart>("Cart", CartSchema);
export default CartModel;cart-item model
lib fucntion to get the cartInfo
import { IProduct } from "@/types/IProduct";
import mongoose, { Document, Schema } from "mongoose";
export interface ICartItem extends Document {
cartId: Schema.Types.ObjectId;
productItem: IProduct;
quantity: number;
}
const CartItemSchema: Schema = new Schema(
{
cartId: {
type: Schema.Types.ObjectId,
ref: "Cart",
required: true,
},
productItem: {
type: Schema.Types.ObjectId,
ref: "Product",
required: true,
},
quantity: { type: Number, default: 0, required: true },
},
{ timestamps: true }
);
const CartItemModel: mongoose.Model<ICartItem> =
mongoose.models.CartItem ||
mongoose.model<ICartItem>("CartItem", CartItemSchema);
export default CartItemModel; lib fucntion to get the cartInfo
export const fetchShoppingCartInfo = async (): Promise<
ICartInfoReturnValues
> => {
try {
const response = await fetch(`/api/cart`);
if (!response.ok) {
console.log("Failed to fetch data");
return;
}
const data = await response.json();
return data;
} catch (error) {
console.log("Error fetching cart info info:", error);
}
};