首页 > 解决方案 > 如何从 MongoDB 中具有多个集合的数据库中访问单个集合数据

问题描述

我正在构建一个快速应用程序,它可以访问 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\gssrDB\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.

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

标签: databasemongodbexpressmongoose

解决方案


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

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

推荐阅读