Skip to content Skip to sidebar Skip to footer

Nodejs Mongodb Dynamic Collection Name

I have several mongodb collections, Fruits: [ {}, {}, {} ...], Bread: [{}, {}, {} ...] I want to use dynamic collection name in my server like // :collection will be 'Fruits'

Solution 1:

You can use the different collections using db.collection('name').find({})

Here is the code i have tried App.js

const express = require('express');
const bodyParser = require('body-parser');

constMongoClient = require("mongodb").MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
var db;

MongoClient.connect(url, { useNewUrlParser: true }, function (err, client) {
assert.equal(null, err);
console.log("Connected successfully to DB");
db = client.db('name of the db');
});

var app=express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/test/:collection', function(req,res){
let collection = req.params.collection;
console.log(collection);
db.collection(collection).find({}).toArray( function (err, result) {
    res.send(result);
    });
});

var port = 8000
app.listen(port, '0.0.0.0', () => {
    console.log('Service running on port ' + port);
});

Hope this helps

Solution 2:

This is not working as the collection name you are passing is just a variable with no DB cursor.

Here's what you can do here:

Create an index.js file, import all the models in that file with proper names as keys.

eg:

const model = {
    order: require("./order"),
    product: require("./product"),
    token: require("./token"),
    user: require("./user")
}

module.exports = model;

Let's assume your request URL is now.

/fetch/user

Now import this index.js as model in your controller file.

eg:

const model = require("./index");

Now you can pass the key as params in your request like and use like it is stated below:

app.get('/fetch/:collection', function (req, res){

    model[req.params.collection].find({}, function(err, docs){
        res.json(docs) // All user data.
    }) 
})

Hope this solves your query!

Solution 3:

I will give solution for this but I don't know is this as per developer standards

let your model names, fruit.js and bread.js in model folder

app.get('/fetch/:collection', function (req, res){
let collectionName = require(`./models/${req.params.collection}`)

collectionName.find({}, function(err, docs){
    res.json(docs)
  }) 
})

Hope this will work

Post a Comment for "Nodejs Mongodb Dynamic Collection Name"