I am learning to use Mongoose with NextJS and I keep running into this error. I have looked over similar questions but didn't figure out how to solve this. I have followed a tutorial video for implementing Mongoose step by step but in the video this problem didn't occur. Also, I hate to say it this inaccurately but it only happens "sometimes". Seems like every time I run the server first POST request always goes through, GET requests are also fine but when I try multiple POST requests it occurs. After restarting the server it works again. Here is my code:
import mongoose from "mongoose"
const connection = {}
async function dbConnect() {
if (connection.isConnected) {
retrun
}
const db = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
connection.isConnected = db.connections[0].readyState
console.log(connection.isConnected)
}
export default dbConnect
const mongoose = require("mongoose")
let NoteSchema = new mongoose.Schema({
email: {
type: String,
required: [true, "Please enter your email"]
}
})
module.exports = mongoose.model.Note || mongoose.model("Note", NoteSchema);
import dbConnect from "../../utils/dbConnect"
import Note from "../../models/Note"
dbConnect()
export default async (req, res) => {
const { method } = req
switch(method) {
case "GET":
try {
const notes = await Note.find({})
res.status(200).json({ success: true, data: notes })
} catch (error) {
res.status(400).json({ success: false })
}
break
case "POST":
try {
const note = await Note.create(req.body)
res.status(201).json({ success: true, data: note })
} catch (error) {
res.status(400).json({ success:false })
}
break
default:
res.status(400).json({ success:false })
break
}
}
Thanks for any help.
所有评论(0)