我无法在mongoDB中从下一个js应用程序创建文档,有人能告诉我如何做到这一点吗

rdrgkggo  于 2023-11-17  发布在  Go
关注(0)|答案(1)|浏览(132)

这是我的connectDB.js文件

import mongoose from 'mongoose'


const connectDB = async () => {
  
  mongoose.connect(process.env.MONGO_URI)

};

export default connectDB;

字符串
这是我的Product.model.js文件

import mongoose from "mongoose";

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

export default mongoose.models.Product || mongoose.model("Product", productSchema)


这是/api/product. js文件

import connectDB from "@/libs/connectDB"
import Product from "@/models/Product.model.js"



export default async function handler(req, res) {

  try {
    console.log("CONNECTING TO DB");
    await connectDB()
    console.log("CONNECTED TO DB");
    if (req.method === 'GET') {
      // const products = await Product.find()
      res.status(200).json({ d: "products" })
    }

    if (req.method === 'POST') {
      console.log("creating product")
      const product = await Product.create(req.body)
      console.log("created product")
      res.status(201).json({ product })
    }

    res.status(400).json({ error: 'Bad Request' })

  } catch (err) {
    console.log(err);
    res.status(500).json({ error: err })
  }

}


当我创建一个post请求到/API/products时,我得到了这种类型的错误:
MongooseError:操作products.insertOne()缓冲在10000 ms后超时,位于进程中的listOntario(node:internal/timers:573:17)。processTimers(node:internal/timers:514:7)error - unhandledRejection:Error [MongooseServerSelectionError]:connect EASPMENT REFUSED::1:27017 at _NativeConnection.openUri { digest:undefined }

lztngnrs

lztngnrs1#

我认为这个错误是因为你的连接良好的数据库是不是建立在正确的方式我读了mongoose仓库,他们建议这个代码连接mongoose在nextjs和这个连接代码也将缓存数据,这将有助于不继续发送请求到数据库,这将使您的应用程序更快,更有效
在connectDB.js文件中,只需编写以下代码

import mongoose from 'mongoose'

const MONGODB_URI = process.env.MONGO_URI

mongoose.set('strictQuery', false);

if (!MONGODB_URI) {
  throw new Error(
    'Please define the MONGODB_URI environment variable inside .env.local'
  )
}

/**
 * Global is used here to maintain a cached connection across hot reloads
 * in development. This prevents connections growing exponentially
 * during API Route usage.
 */
let cached = global.mongoose

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null }
}

async function dbConnect() {
  if (cached.conn) {
    return cached.conn
  }

  if (!cached.promise) {
    const opts = {
      bufferCommands: false,
    }

    cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
      return mongoose
    })
  }

  try {
    cached.conn = await cached.promise
  } catch (e) {
    cached.promise = null
    throw e
  }

  return cached.conn
}

export default dbConnect

字符串

相关问题