mongodb 类型错误:_模型_产品__WEBPACK_IMPORTED_MODULE_1__.default.find不是函数

wvyml7n5  于 2022-11-03  发布在  Go
关注(0)|答案(2)|浏览(951)

我正在制作Next Js Web应用程序,browesr在第一个代码块的第7行显示类型错误。错误位于Product.find()下
类型错误:models_Products__WEBPACK_IMPORTED_MODULE_1_。默认值。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;

`

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

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)
0vvn1miw

0vvn1miw1#

尝试如下导出您的model

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

您可以删除mongoose.models = {}行。

z9ju0rcb

z9ju0rcb2#

这对我很有效“ Mongoose ”:“^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;

相关问题