database - 如何从 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.
如何访问每个集合下的数据?
解决方案
由于数据库中有多个集合,因此需要使用单独的回调函数。这可以通过首先连接到第二个数据库并使用回调函数访问请求的集合来完成。
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)
})
})
推荐阅读
- html - 有没有办法放入样式表以获取页面上所有表单元素的 Material 主题或类似主题?
- java - 即使 3 个节点中只有 1 个启动,Kafka 生产者也会继续生成消息
- ios - 如何检查代码和情节提要中的segues是否正确链接?“as!”中的感叹号 是不是也没有突出显示?
- modbus - 如何读取 modbus RTU 保持寄存器的全长(添加 40001 : 49999)?
- python - 如何使用 GMSH 或类似工具从 .step 文件中自动生成网格?
- swift - 在 Xcode 中构建 Firebase 登录
- excel - 仅使用带有自动过滤器的用户界面来保护带有宏的工作簿不起作用
- swift - 将字符串转换为日期对象时出现问题
- javascript - 打开和关闭模式后重复数据
- c# - 基于屏幕大小的水平与垂直导航栏