我正在使用Nextjs创建电子商务应用程序,并在该应用程序中使用Mongoose我有这个productSchema (models/Product):
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema(
{
title: { type: String, required: true },
slug: { type: String, required: true, unique: true },
desc: { type: String, required: true },
category: { type: String, required: true },
size: { type: String },
color: { type: String },
price: { type: Number, required: true },
title: { type: String, required: true },
availableQty: { type: Number, required: true },
img: { type: String, required: true },
},
{ timestamps: true }
);
export default mongoose.model("Product", productSchema);
getProducts api (api/getProducts):
import Product from "../../models/Product";
import connectDb from "../../middleware/mongoose";
const handler = async (req, res) => {
let products = await Product.find();
res.status.json({ products });
};
export default connectDb(handler);
这是mongoose.js文件(middleware/mongoose):
import mongoose from "mongoose";
const connectDb = (handler) => async (req, res) => {
if (mongoose.connections[0].readyState) {
return handler(req, res);
}
await mongoose.connect(process.env.MONGO_URI);
return handler(req, res);
};
export default connectDb;
当我打开api/getProducts在浏览器中,我得到的错误:TypeError: mongoose.model()不是一个函数。
我怎么能解决这个问题?问题是什么?
有两个相同名称的字段,"title">尝试更改名称,这样就不会有两个具有相同模式的字段。程序现在应该可以工作了。我用我建议的更改运行了模型文件,但我没有得到错误。