Nodejs mongodb 动态集合名称 [英] Nodejs mongodb dynamic collection name

查看:53
本文介绍了Nodejs mongodb 动态集合名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个mongodb集合,

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)
    }) 

})

但如您所知,[req.params.collection].find()... 不起作用.如何使用动态集合名称?

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

推荐答案

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

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:

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

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

例如:

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

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

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

例如:

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!

这篇关于Nodejs mongodb 动态集合名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆