我试图在NextJS中使用mongoose进行POST请求。我有lib/dbConnect.js
,models/User.js
,app/new/route.ts
。app/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
文件。
2条答案
按热度按时间ndh0cuux1#
你的
app/new/route.ts
是这样的吗:除了
route.ts
之外,你还可以使用NextJS的服务器动作来请求数据库插入数据。然而,这可能需要进一步澄清客户端或服务器端组件。大概是这样的:
lib/user.action.ts
oyt4ldly2#
我最终得到了一个稍微不同的
route.ts
。我把它记为app/api/users/route.ts
。下面是这个文件的内容: