关于MongoDB数据库的安装这里不再赘述,网上教程很多,自行百度哈。
npm i -D nuxt-mongodb2.接下来,在nuxt.config.ts文件中进行配置:
//nuxt.config.ts export default defineNuxtConfig({ modules: ['nuxt-mongodb'], })3.然后,就是进行关于mongoDB数据库连接的配置:
//.env MONGO_CONNECTION_STRING={{你的数据库链接字符串}} MONGO_DB={{你的数据库名称}}例如:
//.env MONGO_CONNECTION_STRING="mongodb://127.0.0.1:27017" MONGO_DB="myDatabase"💡最后,在你的server目录中创建api.js文件用于调用数据库:
//api.js import { mongo } from '#nuxt-mongodb' const db = mongo.db() const response = await db.collection('你的集合名称').find()例如:
//api.js import { mongo } from '#nuxt-mongodb' const db = mongo.db() const response = await db.collection('myTestCollection').find()至此,我们连接数据库的步骤就完成了!
// findSQL.ts /* * 堆代码 duidaima.com * @FilePath: \AIGC_Course_frontend\server\curd\findSQL.ts * @Description: mongoDB数据库查询方法封装 */ import { mongo } from '#nuxt-mongodb' /** * 数据库查询方法 * @param table 数据集合 * @param obj 查询对象 * @returns 返回查询结果 * @example * findSQL("myTestCollection",{"age": 21}) */ export const findSQL = async (table: string, obj: object = {}) => { return new Promise(async (resolve, reject) => { const db = mongo.db() try { const response = await db.collection(table).find(obj).toArray() //注意此处的toArray()方法,否则可能返回的数据无法正常访问 resolve(response) db.close(); } catch (error) { reject(error) } }) }对上述封装的调用示例:
// app.js * @FilePath: \AIGC_Course_frontend\server\api\app.ts * @Description: 数据库查询方法的调用 // 引入自行封装的查询方法 import { findSQL } from '../curd/findSQL' export default defineEventHandler(async (event: any) => { // 此处获取并解析前端接口传来的body参数,详情参见https://nuxt.com.cn/docs/guide/directory-structure/server#%E7%94%A8body%E5%A4%84%E7%90%86%E8%AF%B7%E6%B1%82 const body = await readBody(event) // 此处调用自行封装的查询方法并填入相关参数 const data = await findSQL('myTestCollection', body) //例如: findSQL("myTestCollection",{"age": 21}) return { code:200, msg: 'ok', data: data } })更多使用示例例如:
// getSwiper.js /* * @FilePath: \AIGC_Course_frontend\server\api\getSwiper.ts * @Description: 使用数据库查询方法的查询轮播图列表数据 */ import { findSQL } from '../curd/findSQL' export default defineEventHandler(async (event: any) => { try { const data = await findSQL('swiper') // 成功时返回状态码和数据信息 return { code: 200, msg: 'ok', data: data } } catch (error: any) { // 失败时返回错误码和错误信息 return { code: 500, msg: error.message } } })在这篇博客中,我分享了如何在 Nuxt.js 3.0 中使用 MongoDB 数据库的经验。主要步骤包括: