Mongodb Moongose 日志表

问题描述

我对如何创建在自己的表中写入数据的日志表感兴趣,每次用户提出一些请求。 以及如何获取这样的数据:

{
            _id: ObjectId('4f442120eb03305789000000'),host: "127.0.0.1",logname: null,user: 'frank',time: ISODate("2000-10-10T20:55:36Z"),path: "/apache_pb.gif",request: "GET /apache_pb.gif HTTP/1.0",status: 200,response_size: 2326,referrer: "[http://www.example.com/start.html](http://www.example.com/start.html)",user_agent: "Mozilla/4.08 [en] (Win98; I ;Nav)"
            }

也许不是所有这些数据,但至少是谁提出了请求,请求的类型,路径和时间。 我正在使用 nodejs、mongodb、mongoose。

解决方法

您可以编写一个 middleware,将发送到您的服务器的所有请求记录到 MongoDB 数据库中。

使用这些 npm 包,您可以轻松获取您要查找的信息,

1 - useragent

2 - express-useragent

,

我就是这样解决的。

我的中间人

const Log = require("../models/log");

const log = async (req,res,next) => {
    try {

    let user_id = req.user.id
    let firstName = req.user.firstName
    let method = req.method
    let path = req.path    

    const log = new Log({ user_id,firstName,method,path });

    try {
        await log.save()
    } catch (e) {
        res.status(400).send(e)
    }

      next();
    } catch (e) {
      res.status(401).send(e);
    }
  };

module.exports = log;

型号

const mongoose = require('mongoose')

const logSchema = new mongoose.Schema({
    user_id: {
        type: String,},firstName: {
        type: String,method: {
        type: String,path: {
        type: String,{
    timestamps: true
})

const Log = mongoose.model('Log',logSchema);

module.exports = Log;

和路由器

const express = require('express')
const Log = require('../models/log')
const auth = require('../middleware/auth')
const router = new express.Router()

//Create log
router.post('/logs',async (req,res) => {
    const log = new Log({
        ...req.body
    })

    try {
        await log.save()
        res.status(201).send(log)
    } catch (e) {
        res.status(400).send(e)
    }
})

//Sort and search
router.get('/logs',auth,res) => {
    const match = {}
    const sort = {}

    if (req.query.completed) {
        match.completed = req.query.completed === 'true'
    }

    if (req.query.sortBy) {
        const parts = req.query.sortBy.split(':')
        sort[parts[0]] = parts[1] === 'desc' ? -1 : 1
    }

    try {
        await req.user.populate({
            path: 'logs',match,options: {
                limit: parseInt(req.query.limit),skip: parseInt(req.query.skip),sort
            }
        }).execPopulate()
        res.send(req.user.logs)
    } catch (e) {
        res.status(500).send()
    }
})

module.exports = router;

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...