简体   繁体   中英

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" or "Bread" 

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

    [req.params.collection].find({}, function(err, docs){
        res.json(docs)
    }) 

})

But as you know, [req.params.collection].find()... isn't working. How can I use dynamic collection name?

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');

const MongoClient = 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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM