MelonBlog

next.js集成mongodb

最近想统计一下博客的访问情况,所以准备集成一个mongodb,用于记录访问情况。

mongoose

mongoose是一个node.js的mongodb框架,包含了一系列开箱即用的功能。

安装

npm install mongoose --save

连接mongodb

创建一个connection.ts

import mongoose, {Schema} from "mongoose";
export const connection = async () => {
    const url = `mongodb://${process.env.MONGO_HOST}:${process.env.MONGO_PORT}`
    console.log('url: ', url);
    return mongoose.connect(url, {
        user: process.env.MONGO_USER,
        pass: process.env.MONGO_PWD,
        dbName: process.env.MONGO_SCHEMA,
    });
}
export const disconnect = async () => mongoose.disconnect();
export const testConnection = async () => {
    // 防止重复连接
    if (mongoose.connection.readyState === 0) {
        await connection();
    }
    const Test = mongoose.model('test', new Schema({title: String}));
    const query = Test.findOne()
    const test = await query.exec();
    console.log(test);
}

让next.js服务启动的时候连接mongo

可以利用next.js的instrumentation.ts功能,在启动的时候执行一段逻辑(可以参考另外一篇博客:https://www.tiangua.info/blog/793b7194-5277-4efd-a5d3-c25c7b311d5e


import {testConnection} from "@/server/dao/connection";
export async function register() {
    console.log("启动完成")
    console.log(process.env["MONGO_URI"])
    await testConnection()
}

定义schema

schema相当于mysql中的表,mongoose要操作schema,需要为每一个schema创建一个映射对象.

下面我定义了一个access_logs表,用于保存用户的访问记录

schema.ts

import {Schema} from "mongoose";
export const AccessLogModelSchema = new Schema({
    page_id: String,
    title: {
        type: String,
        default: '',
        required: false
    },
    date: String,
    ip: String,
    city: {
        type: String,
        default: '',
        required: false
    },
    country: {
        type: String,
        default: '',
        required: false
    },
    region: {
        type: String,
        default: '',
        required: false
    },
    latitude: {
        type: String,
        default: '',
        required: false
    },
    longitude: {
        type: String,
        default: '',
        required: false
    },
});

保存数据到schema

mongo.ts

import mongoose from 'mongoose';
import {AccessLogModelSchema} from './schema';
import {connection} from './connection';
export const saveAccessLog = async (log: {
    page_id: string,
    title?: string,
    date: string,
    ip: string,
    city?: string,
    country?: string,
    region?: string,
    latitude?: string,
    longitude?: string,
}) => {
    // 防止重复连接
    if (mongoose.connection.readyState === 0) {
        await connection();
    }
    const Model = mongoose.model('access_log', AccessLogModelSchema)
    const accessLog = new Model(log);
    await accessLog.save();
}

友情链接


Copyright © 2023 www.tiangua.info 鄂ICP备2022015834号