如何在NextJS v13.4中使用mongoose发出POST请求?

btqmn9zl  于 2023-10-19  发布在  Go
关注(0)|答案(2)|浏览(119)

我试图在NextJS中使用mongoose进行POST请求。我有lib/dbConnect.jsmodels/User.jsapp/new/route.tsapp/new/route.ts是包含表单的页面的文件,我们将从其中发出POST请求。下面是我的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'
  )
}

/**
 * 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;

以下是我的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)

老实说,我真的不知道如何在里面写app/new/route.ts和POST请求。我在网上找不到。我见过一些人使用中间件,但我不知道如何更改我的dbConnect.js文件。

ndh0cuux

ndh0cuux1#

你的app/new/route.ts是这样的吗:

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)
    }

}

除了route.ts之外,你还可以使用NextJS的服务器动作来请求数据库插入数据。然而,这可能需要进一步澄清客户端或服务器端组件。
大概是这样的: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}`)
    }

}
oyt4ldly

oyt4ldly2#

我最终得到了一个稍微不同的route.ts。我把它记为app/api/users/route.ts。下面是这个文件的内容:

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,
        })
    }
}

相关问题