繁体   English   中英

Nodejs mongodb动态集合名称

[英]Nodejs mongodb dynamic collection name

我有几个mongodb集合,

 Fruits: [ {}, {}, {} ...],
 Bread: [{}, {}, {} ...]

我想在我的服务器中使用动态集合名称

// :collection will be "Fruits" or "Bread" 

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

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

})

但是如你所知, [req.params.collection].find()...无效。 我如何使用动态集合名称?

您可以使用db.collection('name')来使用不同的集合.find({})

这是我试过的代码
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);
});

希望这可以帮助

这不起作用,因为您传递的集合名称只是一个没有DB光标的变量。

这是你在这里可以做的:

创建一个index.js文件,导入该文件中的所有模型,并使用适当的名称作为键。

例如:

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

module.exports = model;

我们假设你的请求URL现在是。

/fetch/user

现在将此index.js导入为控制器文件中的模型。

例如:

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

现在您可以将密钥作为params传递给您的请求,并使用如下所述:

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

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

希望这能解决您的疑问!

我会为此提供解决方案,但我不知道这是否符合开发人员标准

让你的模型名称,fruit.js和bread.js在模型文件夹中

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

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

希望这会奏效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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