Currently, I am faced with the challenge of executing a POST request using mongoose in NextJS. In my project structure, I have three key files: lib/dbConnect.js
, models/User.js
, and app/new/route.ts
. As defined, app/new/route.ts
is responsible for handling the form page where the POST request will be initiated. Let's take a closer look at my lib/dbConnect.js
:
import mongoose from 'mongoose'
const MONGODB_URI = process.env.MONGODB_URI
if (!MONGODB_URI) {
throw new Error(
'Please define the MONGODB_URI environment variable inside .env.local'
)
}
/**
* To ensure connection persistence across hot reloads in development,
* we utilize "Global" to maintain a cached connection.
*/
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;
Moving on to models/User.js
:
import mongoose from 'mongoose'
/* UserSchema maps to a designated collection in MongoDB database */
const UserSchema = new mongoose.Schema({
name: {
/* User's name */
type: String,
required: [true, 'Please provide your name.'],
maxlength: [60, 'Name cannot exceed 60 characters'],
},
email: {
/* User's email address */
type: String,
required: [true, "Please provide your email."],
maxlength: [60, "Email cannot exceed 60 characters"],
},
password: {
/* User's password */
type: String,
required: [true, 'Please provide your password.'],
maxlength: [60, 'Password must not exceed 40 characters'],
},
// dob: {
// /* User's DOB */
// type: Date,
// required: true,
// },
country: {
/* User's country */
type: String,
required: [true, 'Please provide your country.'],
maxlength: [60, 'Country must not exceed 40 characters'],
},
})
export default mongoose.models.User || mongoose.model('User', UserSchema)
Admittedly, I'm struggling with defining app/new/route.ts
and implementing the POST request within it. Resources online haven't provided sufficient guidance. While some references mention middleware utilization, I've yet to decipher how to incorporate this into my existing dbConnect.js
file.