Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call dynamic collection in mongoose?

How to convert a string as a parameter into a collection model in nodejs?
So when someone visits example.com/?table=products, I want to access the products collection. How can I do that?

route.get("/products", async (req, res) => {

    var symbol = req.query.symbol;
    if (symbol == null) {
        res.json({ 'status': 'fail', 'msg': 'symbol not found' });
        return;
    }
    const sampleScheme = new mongoose.Schema({
        price : String
    }, {versionKey : false, strict: false});
    
    
   let model = await db.model(symbol, sampleScheme);
   var data = await model.find();
    return res.json({ 'status': 'success', 'data': data });
});

    

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const mongoose = require('mongoose');
const express = require('express');
const route = express.Router();

// Assuming 'db' is your MongoDB connection
// You need to set up your MongoDB connection before using this route

route.get("/products", async (req, res) => {
    const symbol = req.query.symbol;

    if (!symbol) {
        return res.json({ 'status': 'fail', 'msg': 'symbol not found' });
    }

    try {
        // Check if the collection exists in MongoDB
        const collectionExists = await mongoose.connection.db.listCollections({ name: symbol }).hasNext();

        if (!collectionExists) {
            return res.json({ 'status': 'fail', 'msg': 'collection not found' });
        }

        // Define schema for the dynamic model
        const sampleSchema = new mongoose.Schema({
            price: String
        }, { versionKey: false, strict: false });

        // Create or retrieve the dynamic model
        let model = mongoose.models[symbol] || mongoose.model(symbol, sampleSchema);

        // Query the collection using the dynamic model
        const data = await model.find();

        return res.json({ 'status': 'success', 'data': data });
    } catch (error) {
        console.error(error);
        return res.status(500).json({ 'status': 'error', 'msg': 'Internal server error' });
    }
});

module.exports = route;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading