I have a Nuxt project that uses Mongoose and a serverless architecture on Vercel. Locally, I can call my cart API endpoint (located at /server/api/cart/index.get.ts) without issues, but when deployed to Vercel I get the following error when fetching the cart:
Schema hasn't been registered for model "Product" Use mongoose.model(name, schema)
My models are defined in separate files and I ensure that the Product model is imported into the Cart model. For example, in my /server/models/product.model.ts I register the model:
// TypeScript code in /server/models/product.model.ts
import mongoose from 'mongoose'
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
price: { type: Number, required: true },
// ... other fields ...
}, { timestamps: true })
export const Product = mongoose.models.Product || mongoose.model('Product', productSchema)
In my /server/models/cart.model.ts I import the Product model and define the cart:
// TypeScript code in /server/models/cart.model.ts
import mongoose from 'mongoose'
import { Product } from './product.model' // Import to ensure registration
const cartItemSchema = new mongoose.Schema({
product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true },
quantity: { type: Number, required: true, min: 1 }
})
const cartSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true, unique: true },
items: [cartItemSchema]
}, { timestamps: true })
export const Cart = mongoose.models.Cart || mongoose.model('Cart', cartSchema)
I also have a MongoDB plugin in /server/plugins/mongodb.ts to connect to my database:
// TypeScript code in /server/plugins/mongodb.ts
import mongoose from 'mongoose'
export default defineNitroPlugin(async () => {
try {
await mongoose.connect(process.env.MONGO_URI!)
console.log('Connected to MongoDB')
} catch (error) {
console.error('MongoDB connection error:', error)
}
})
In the cart API endpoint (/server/api/cart/index.get.ts), I check for a connection and populate the Product reference:
// TypeScript code in /server/api/cart/index.get.ts
import { Cart } from '~/server/models/cart.model'
import mongoose from 'mongoose'
export default defineEventHandler(async (event) => {
const user = event.context.user
if (!user) {
throw createError({ statusCode: 401, message: 'Unauthorized' })
}
try {
// Ensure that the database connection is ready
if (mongoose.connection.readyState !== 1) {
await mongoose.connect(process.env.MONGO_URI!)
}
// Fetch the cart and populate the product field
const cart = await Cart.findOne({ user: user._id }).populate('items.product')
if (!cart) {
return { message: 'Cart is empty', cart: { items: [] } }
}
return { cart }
} catch (error) {
throw createError({
statusCode: 500,
message: 'Failed to fetch cart',
data: error instanceof Error ? error.message : error
})
}
})
The error only appears on Vercel (serverless cold starts) and not on my local machine in my local machine it's work and give me response. The Request and response:
curl 'http://localhost:3000/api/cart' \
-H 'sec-ch-ua-platform: "macOS"' \
-H 'authorization: Bearer ACCESS_TOKEN' \
-H 'Referer: http://localhost:3000/' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36' \
-H 'sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"' \
-H 'sec-ch-ua-mobile: ?0'
{
"cart": {
"_id": "67c90694567113547cc060bd",
"user": "67c7739f0f6280db6e68912c",
"items": [
{
"product": {
"_id": "67c6e618fdf99521dc4da4c9",
"name": "Test Product",
"price": 9.99,
"description": "Test description",
"available": true,
"stockCount": -2,
"images": [],
"author": "Test Author",
"hasDiscount": false,
"discountPercentage": 0,
"visible": true,
"isAllowCoupon": false,
"bookType": "paperback",
"category": "story",
"createdBy": "67c6d57dceae787650a6eb84",
"createdAt": "2025-03-04T11:38:00.145Z",
"updatedAt": "2025-03-04T15:27:37.161Z",
"__v": 0,
"ratingAverage": 5,
"ratingCount": 1
},
"quantity": 2,
"_id": "67c90694567113547cc060bf"
}
],
"createdAt": "2025-03-06T02:21:08.103Z",
"updatedAt": "2025-03-06T02:21:08.332Z",
"__v": 1
}
}%
❯
❯ curl '/api/cart' \
-H 'sec-ch-ua-platform: "macOS"' \
-H 'authorization: Bearer ACCESS_TOKEN' \
-H 'Referer: /' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36' \
-H 'sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"' \
-H 'sec-ch-ua-mobile: ?0'
{"url":"/api/cart","statusCode":500,"statusMessage":"","message":"Failed to fetch cart","stack":"","data":"Schema hasn't been registered for model \"Product\".\nUse mongoose.model(name, schema)"}
I'm wondering:
Could the error be related to the import order or timing of model registration in a serverless environment? Is it necessary to enforce the connection or model registration in a specific manner on Vercel? What changes should be made to ensure the Product model is registered before it’s referenced by Cart? Any help on how to resolve this error would be appreciated.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744971261a4603979.html
评论列表(0条)