skip to Main Content

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


  1. Chosen as BEST ANSWER

    I ended up having a slightly different route.ts. I put it as app/api/users/route.ts. Here is the content of this file:

    import { NextRequest, NextResponse } from "next/server";
    import dbConnect from '../../../lib/dbConnect'
    import User from '../../../models/User'
    
    export async function POST(req: NextRequest, res: NextResponse) {
        const data = await req.json();
        await dbConnect();
    
        try {
            const user = await User.create(
                data
            ) /* create a new model in the database */
            return NextResponse.json({
                success: true,
                data: user,
                message: "Success"
            }, {
                status: 201,
            })
        } catch (error) {
            return NextResponse.json({
                success: false,
                message: "Fail",
            }, {
                status: 400,
            })
        }
    }
    

  2. Is your app/new/route.ts similar to this:

    import User from "models/User.js";
    import dbConnect from "lib/dbConnect.js";
    import { NextRequest, NextResponse } from 'next/server';
    
      dbConnect()
    
    export async function POST(request: NextRequest) {
        try {
            const reqBody = await request.json()
            const { username, email, password } = reqBody
    
            const newUser = new User({
                username,
                email,
                password: hashedPassword
            })
    
            const savedUser = await newUser.save()
    
            return NextResponse.json({
                message: "User created successfully",
                sucess: true,
                savedUser
            }
    
        } catch(err) {
    
         console.log(err)
        }
    
    }
    

    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

    import User from "models/User.js";
    import dbConnect from "lib/dbConnect.js";
    
    
    export async function updateUser() {
    
       dbConnect()
    
       try {
            await User.findOneAndUpdate(
                {
                    email: email.toLowerCase(),
                    name,
                    password,
                    country
                },
                { upsert: true }
            )
    
     
        } catch (error) {
            throw new Error(`Failed to create/update user: ${error.message}`)
        }
    
    }
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search