'Use collection get from req.params - node.js

I'm using node.js and mongodb I need to know how to request the reading of a certain collection via API (day_07-07-2021 is the collection to search)

in the Node.js route I wanted to query the collection day07072021, I wanted to know how I change the collection (on the fly) to query the route using the "req.param" received via URL. so after setting the collection I'll do find();

Each day will have a collection.

http://localhost:3000/registry/windows2021/1101/day07072021

My actual code is (updated after: Selva Mary), but still not working.

logs.js

    const express = require('express')
    const router = express.Router()
    const logs = require('../models/registry')
    
    
        router.get('/:device/:rule/:bydate', async (req, res) => {
           try {
           let byDate = req.params.bydate +"info" 
           const logues = await db.collection(byDate).find({
              'agent.name': req.params.device,
              'rule.id': req.params.rule
            }).sort({ 'id': -1 }).limit(15);
            res.json(logues)
          }
          catch (err) {
            res.status(500).json({ message: err.message })
          }
        })

server.js

require('dotenv').config()

const express = require('express')
const app = express()
const mongoose = require('mongoose')
const log = mongoose.set('debug', true)


mongoose.connect('mongodb://db:27017/datainfo', { useNewUrlParser: true,useUnifiedTopology: true })
const db = mongoose.connection

const registryRouter = require('./routes/registry')
app.use('/registry', registryRouter)

I hope its clear.

I get the message: {"message":"db is not defined"}



Solution 1:[1]

Try this

   router.get('/:device/:rule/:bydate', async (req, res) => {
       try {
let byDate = req.params.bydate +"" // this makes the bydate as string. Collection name need to be in string
        const logues = await logs.collection(byDate).find({
          'agent.name': req.params.device,
          'rule.id': req.params.rule
        }).sort({ 'id': -1 }).limit(15);
        res.json(logues)
      }
      catch (err) {
        res.status(500).json({ message: err.message })
      }
    })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Selva Mary