如何从 MongoDB 中具有多个集合的数据库中访问单个集合数据

Posted

技术标签:

【中文标题】如何从 MongoDB 中具有多个集合的数据库中访问单个集合数据【英文标题】:How to access individual collection data from a database with multiple collections in MongoDB 【发布时间】:2021-07-30 23:32:07 【问题描述】:

我正在构建一个快速应用程序,它可以访问 MongoDB 中至少两个不同的数据库。我能够使获取路线适用于单个数据库。但我需要访问另一个有多个集合的数据库。

这是模型文件

allModels.js

const mongoose = require('mongoose');

const  tgsConnection, dMaxConnection = require('../connection/connections');

// create schema
const tgSchema = new mongoose.Schema(
    name: 
        type: String,
        required: true
    ,
    lon: 
        type: Number,
        required: true,
    ,
    lat: 
        type: Number,
        required: true,
    ,
    country: 
        type: String,
        required: true,
    ,
)


const dmaxSchema = new mongoose.Schema(
    date: 
        type: String,
        required: true
    ,
    surge: 
        type: Number,
        required: true,
    ,
    ymd: 
        type: String,
        required: true,
    ,
    lon: 
        type: Number,
        required: true,
    ,
    lat: 
        type: Number,
        required: true
    
,
     collection : 'Dmax'
)

// compile our model
const TideGauge = tgsConnection.model('TideGauge', tgSchema);
const Dmax = dMaxConnection.model('Dmax', dmaxSchema);

// export model
module.exports = 
    TideGauge,
    Dmax,
;

Dmax 模型下,我已经导入了 882 个集合(使用 mongoimport 导入了 882 个 csvs),我想以 get 请求的形式访问这些导入的集合,如下所示:

    // get observed surge
    app.get('/alltgs/:id/obs_surge', async (req, res) => 
        const  id  = req.params;
        const tg = await TideGauge.find(_id : id);
        const tgName = tg[0].name;
        console.log(`tide gauge name is: $tgName`);
        const tgDmax = await Dmax.aguadilla,pr_263a_usa.find();
        console.log(tgDmax);
    )

我尝试使用Dmax.find()Dmax.collectionName.find() 来访问存储在集合下的数据,但没有成功。相反,我收到以下错误

[nodemon] starting `node index.js`
app is listening on port 4000
MongoDB :: connected allTgs
MongoDB :: connected dailyMaxSurge
MongoDB :: allTgs tidegauges.find("_id":"60950ed93f528b6b344921cd","projection":)
tide gauge name is: aguadilla,pr_263a_usa
(node:2280) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'find' of undefined
    at C:\Users\mi292519\OneDrive\gs-s-rDB\index.js:98:54
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2280) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:2280) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

如何访问每个集合下的数据?

【问题讨论】:

【参考方案1】:

由于数据库中有多个集合,需要使用单独的回调函数。这可以通过首先连接到第二个数据库并使用回调函数访问请求的集合来完成。

 app.get('/alltgs/:id/obs_surge', async (req, res) => 
    const  id  = req.params;
    const tg = await TideGauge.find(_id : id);
    const tgName = tg[0].name;
    console.log(`tide gauge name is: $tgName`);
    
    // connect to the dmax db
    mongoose.connect('mongodb://localhost:27017/dailyMaxSurge',    useNewUrlParser: true, useUnifiedTopology: true)
    .then(() => 
        console.log("connected to dailyMaxSurge")

        mongoose.connection.db.collection(tgName, function (err, collection) 
            collection.find().toArray(function(err, data)
            // console.log(data); // it will print your collection data
            const timeSeries = data;
            res.send(timeSeries);
        );
   );
    )
    .catch(err => 
        console.log('unable to connect to dailyMaxSurge')
        console.log(err)
    )
)

【讨论】:

以上是关于如何从 MongoDB 中具有多个集合的数据库中访问单个集合数据的主要内容,如果未能解决你的问题,请参考以下文章

如何从 MongoDB 集合中获取具有匹配键的最后 N 个元素

如何从 MongoDB 集合中获取具有匹配键的最后 N 个元素

如何使用graphql将mongodb中多个集合中的数据传递到1个反应表

MongoDB:如何使用 expressjs 从所有集合中读取所有文档?

MongoDB:如何使用 expressjs 从所有集合中读取所有文档?

MongoDB:将来自多个集合的数据合并为一个..如何?