【发布时间】: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\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.
如何访问每个集合下的数据?
【问题讨论】:
标签: database mongodb express mongoose