最近进行了nextjs的学习,在项目中,总归会遇到需要数据的时候,也不想一直使用mock的方式,那就把数据库连接、创建等操作一起学习了吧。
这次我使用的工具有mongodb,mongoose这两个东西。 mongodb请去官网下载并安装。 mongoose需要在项目中使用npm安装。
好了我们完成了前置操作,现在我们一步步进行实际代码编写吧。
1、连接数据库
在nextjs项目中连接数据库有两种方式。 其一就是直接写连接函数,然后放到项目最外层在项目启动的时候执行。 不知道为什么,可能是因为页面会刷新,所以连接函数会多次执行,我这里就会报错,所以我使用的是下面这个方法。
创建lib/db/index.ts
import mongoose from "mongoose";
let cached = (global as any).mongoose;
if (!cached) {
cached = (global as any).mongoose = {
conn: null,
promise: null
}
}
export default async function ConnectDB () {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
};
cached.promise = mongoose.connect('mongodb://127.0.0.1:27017/test', opts).then((mongoose) => {
return mongoose;
});
}
try {
const db_url = 'mongodb://127.0.0.1:27017/test';
// const conn = await mongoose.connect(db_url);
cached.conn = await cached.promise;
console.log(`${db_url} 连接成功`)
} catch(e) {
cached.promise = null
console.error(`Error:{error.message}`);
process.exit(1);
}
return cached.conn;
}
在上面代码中我们创建了一个连接的缓存,如果已连接,会直接返回conn,如果第一次连接,那么会使用mongoose
的connect
方法进行连接数据库操作。
connect
方法主要需要提供2个参数,一个是数据库的url
地址,一个是配置项options
(可选),因为新版会自动使用newUrlParse
等配置, 就不用我们传递了。
数据库地址是mongodb
协议,然后默认是本地27017
端口,可能我是在host
中修改过localhost
对应的ip
,所以我只有127.0.0.1:27017
能成功,/
后面就是你想连接或直接创建的数据库名称了。
好了,那如何使用呢。
别着急我们先去创建一个report的数据表。
2、数据表创建
就在lib/db
下创建models文件夹,在里面创建report.ts
文件
import mongoose from "mongoose";
export interface IReport extends mongoose.Schema {
title: String;
content: String;
createAt: Date;
updateAt: Date;
}
export const ReportSchema = new mongoose.Schema<IReport>({
title: {
type: String,
maxlength: [20, '标题需要少于20个字符'],
required: true,
},
content: {
type: String,
required: true,
},
createAt: {
type: Date,
default: new Date().getTime(),
},
updateAt: {
type: Date,
default: new Date().getTime(),
},
})
export const ReportModel = mongoose.models.Report || mongoose.model('Report', ReportSchema);
在上面代码中,我们定义了数据表字段的类型,并创建了ReportModel
;
注意:在导出的时候需要先判断models中是否已经存在当前表,如果不存在就用model方法创建,如果存在直接返回,如果不这样写,因为在很多接口中我们都会直接import,那么相当于重复创建同名表,会报错。(也可以跟连接数据库一样,放最外层,只在项目启动的时候执行一次)
3、接口编写
这里暂不涉及用户校验操作。
在pages中创建api/port/create.ts
import type { NextApiRequest, NextApiResponse } from "next";
import ConnectDB from "../../../lib/db";
import { ReportModel, IReport } from "../../../lib/db/models/blog";
export default async function handler (req: NextApiRequest, res: NextApiResponse) {
await ConnectDB();
if (req.method === 'POST') {
const {
title,
content,
} = req.body;
const result = await ReportModel.create({ title, content });
res.status(200).send({
code: 0,
msg: 'success',
data: {
item: result
}
})
}
}
4、使用postman测试接口
文章若有错误请在评论区指出