I’m trying to make a POST request with mongoose in NextJS. I have lib/dbConnect.js
, models/User.js
, app/new/route.ts
. app/new/route.ts
is the file for the page with the form, from where we will make a POST request. Here is my lib/dbConnect.js
file:
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'
)
}
/**
* 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;
Here’s my models/User.js
:
import mongoose from 'mongoose'
/* UserSchema will correspond to a collection in your MongoDB database. */
const UserSchema = new mongoose.Schema({
name: {
/* The name of this user */
type: String,
required: [true, 'Please provide your name.'],
maxlength: [60, 'Name cannot be more than 60 characters'],
},
email: {
/* The email of this user */
type: String,
required: [true, "Please provide your email."],
maxlength: [60, "Email cannot be more than 60 characters"],
},
password: {
/* The password of your user */
type: String,
required: [true, 'Please provide your password.'],
maxlength: [60, 'Password specified cannot be more than 40 characters'],
},
// dob: {
// /* User's DOB */
// type: Date,
// required: true,
// },
country: {
/* The country of your user */
type: String,
required: [true, 'Please provide your country.'],
maxlength: [60, 'Country specified cannot be more than 40 characters'],
},
})
export default mongoose.models.User || mongoose.model('User', UserSchema)
Being honest, I really don’t know how to write app/new/route.ts
and POST request inside it. I couldn’t find anything onlinel. I’ve seen some people use middleware but I couldn’t figure out how to change my dbConnect.js
file.
2
Answers
I ended up having a slightly different
route.ts
. I put it asapp/api/users/route.ts
. Here is the content of this file:Is your
app/new/route.ts
similar to this:Alternative to
route.ts
, you can use NextJS’s Server Actions to make the request to database for data insertion. However this may require further clarification on client or server side component.Something like this:
lib/user.action.ts