Table for logging MongoDB operations using Mongoose

I am looking to develop a log table that logs data in its own table every time a user sends a request. I am also interested in retrieving data similar to the following:

{
            _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)"
            }

Not necessarily all of this information, but at least details on who made the request, the type of request, path, and timestamp. I am working with nodejs, mongodb, and mongoose.

Answer №1

If you want to track all incoming requests to your server, consider implementing a custom middleware that logs the data to a MongoDB Database.

To make this task easier, check out these npm packages:

1 - useragent

2 - express-useragent

Answer №2

This is the method I used to solve the problem.

Middleware

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;

Data Model

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;

Router Configuration

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, async (req, 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;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Locate a deeply nested element within an array of objects using a specific string identifier

Trying to search for an object in an array with a matching value as a string can be achieved with the following code snippet. Is there an alternative method to optimize this process without utilizing map? Code: const arr = [{ label: 'A', ...

A guide on querying MongoDB using the PHP extension to retrieve the number of results from a cursor

The mongo PHP extension has been deprecated in favor of the mongodb extension. To use this new extension, it is necessary to also include the mongo-php-library. Previously with the old extension, one could retrieve the result count from a cursor using Mon ...

Searching for a specific character sequence within a MongoDB database

I am looking to create a small file system-like structure in MongoDB. Here is an example of what my object could look like: { "\":{ 'autoexec.bat':{ name:'autoexec', filetype:'bat', ...

Encountering a problem with Vite and PostCSS: "Assignment to invalid left-hand side"

Yesterday everything was running smoothly, but today I encountered an error message saying Invalid left-hand side in assignment. When I checked the Chrome console, it displayed the same error related to a file named ${mod.url} pointing to this source code: ...

Unable to collapse the Bootstrap dropdown menu

For the life of me, I can't seem to find a solution to my problem. I'm currently working on creating a responsive navbar for my website by following a tutorial. The goal is to make it mobile-friendly with a button that expands the menu on smaller ...

Ways to retrieve partial data from mongodb instead of fetching the entire dataset

If I have a collection with 100,000 entries, how can I retrieve only 50 data at a time instead of the entire dataset? It's not practical to fetch the entire dataset in one go. The structure of my dataset is as follows: { "_id" : ObjectId("5a2e28 ...

Morphia fails to identify the @ID annotated field in my code

My problem involves a straightforward POSO called GroupACLTemplate that I am attempting to persist. This class is a subclass of an abstract class, and I have used annotations such as @Entity and @Id. @Entity("aclTemplate") @SerialVersionUID(1L) class Grou ...

React router dom - A tool for efficient navigation in React applications

Today I delved into working with React and react-router-dom. My goal was to create a custom "Route" using my own class, but I am facing a challenge in capturing the id before rendering the page. Here is the code snippet I have been working on: import Reac ...

Is there a way to identify the specific '$or' clause to which each document corresponds in the results of a query?

I'm currently working on developing a small market application using NodeJs and Mongoose. I have created a Market schema as follows; var Market = new Schema({ text: { type: String, required: true }, start_date: Date, loc: { type: { ...

Inactivity for more than 5 minutes causes Spring to disconnect from MongoDB Atlas

Recently, I encountered a minor issue while working with MongoDB Atlas. I created an account on the cloud-based platform for testing purposes and integrated my Spring Boot application with a database on Atlas ( MongoDB Database structure ). Initially, eve ...

Leveraging HTML tables for input purposes

Just starting out with php, HTML, and mysql. Using HTML tables for the first time here. Created an HTML table filled with data from a MySQL table. Planning to use this table as a menu where users can click on a cell with a specific date. The clicked date ...

Retrieving output from a JavaScript function

When running the code, the following logs are generated: "generating my graph" myMain.js:110 "Getting credits" myMain.js:149 "debits array is 3.9,4.2,5.7,8.5,11.9,15.2,17,16.6,14.2,10.3,6.6,4.8" myMain.js:169 "Credits data = 10.7,20.5" myMain.js:156 ...

Retrieving data from an anonymous function in AngularJS and outputting it as JSON or another value

Within the following code, I am utilizing a server method called "getUserNames()" that returns a JSON and then assigning it to the main.teamMembers variable. There is also a viewAll button included in a report that I am constructing, which triggers the met ...

Experiencing a bug in the production build of my application involving Webpack, React, postCSS, and potentially other JavaScript code not injecting correctly

I've encountered an issue with my webpack.prod.config when building my assets, which may also be related to the JS Babel configuration. While I can successfully get it to work in the development build by inline CSS, the problem arises when attempting ...

Exploring the interplay between jQuery functions and the "Class" method in Javascript

Is there a way to reference a parent "class" method in Javascript from a jQuery function? Here's an example scenario: $Object.prototype.TestFunction = function(arg){ alert(arg); } $Object.prototype.foo = function(){ $(something).click(function ...

What is Node.js's approach to managing concurrent operations?

Recently, I've been engrossed in this fascinating book that delves into JavaScript. In one section, it emphasizes that Node.js stands out due to its unique single-threaded event-based concurrency through an asynchronous-by-default API. I find it puz ...

The caret plugin feature in jQuery is dysfunctional in Internet Explorer

After successfully creating a complex script using the jQuery plugin at caret (http://code.google.com/p/jquery-at-caret/), I unfortunately discovered that it only functions properly in Firefox and Chrome, but not in Internet Explorer. The issue seems to b ...

What is the most efficient method for storing counters in a MongoDB database?

Let's take the scenario where we need to store the number of likes and shares for an article. There are two possible methods to achieve this: We can store them as an embedded document stats: { likes_count: 10, shares_count: 5 } Alternative ...

What is the best way to stop an emitter.on from executing within a conditional statement?

Currently, I am working on developing a Discord bot command that can ignore specific commands in particular channels. To unignore a channel, the user must initiate a command, then they will receive a prompt prompting them to reply with "Yes" or "No". If th ...

Steps to activate the context menu for specific elements

I've successfully disabled the context menu (mouse right-click) for the entire document using the following code: $(document).bind('contextmenu',function(){return false;}); Now I'm trying to enable the context menu for a specific in ...