TypeError: _models_products__webpack_importted_module__defau



我正在制作Next Js web应用程序,浏览器在第1块代码中显示第7行类型错误。错误在Product.find()
TypeError:models_products__webpack_importted_module_1_default .find不是一个函数

6 | const handler = async (req, res) => {
>  7 |   let products = await Product.find();
|                       ^
8 |  
9 |   res.status(200).json({ products });
10 | };

**这是我的mongodb数据库**


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;
`

这是我的数据库连接到下一个js应用程序在api文件夹


import connectDb from "../../database";
import Product from "../../models/Products";
const handler = async (req, res) => {
let products = await Product.find();
res.status(200).json({ products });
};
export default connectDb(handler);

*这是我的产品架构


const mongoose=require("mongoose")
const productSchema=new mongoose.Schema({
title:{
type:String,
required:true
},
slug:{
type:String, required:true
},
desc:{type:String,required:true},
img:{type:String,reuired:true},
category:{type:String,reuired:true},
size:{type:String},
color:{type:String},
price:{type:Number},
availableQty:{type:String,required:true}

},{timestamps:true});
mongoose.models={}
export default mongoose.model=('Product',productSchema)

尝试像这样导出您的model:

export default mongoose.models?.Product || mongoose.model('Product', productSchema);

可以去掉mongoose.models = {}线。

这对我有用"猫鼬"; "^6.7.0"与nextjs→使用这个作为引用

import { Schema, model, models } from "mongoose";
const UserSchema = new Schema({
displayName: { type: String, required: true },
email: { type: String, required: true, unique: true },
phone: { type: String, unique: true },
password: { type: String },
pro: { type: Boolean, default: false },
author: { type: Boolean, default: false },
photoURL: { type: String },});
console.log(model); // undefined
console.log(models.UserModel); //this solved

const User = models.UserModel;
export default User;

相关内容

  • 没有找到相关文章

最新更新