我一直在尝试使用MongoDB
将我的应用程序连接到express
,但是没有成功。在代码最重要的部分下面:
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var mongoose = require('mongoose');
const bodyParser = require('body-parser');
const vesselController = require('./controllers/VesselController');
require('./config/keys');
var app = express();
app.use(cors());
app.options('*', cors());
// DB Config
const db = require('./config/keys').MongoURI;
const options = {
useNewUrlParser: true,
reconnectTries: Number.MAX_VALUE,
poolSize: 10
};
mongoose
.connect(db, options)
.then(() => console.log('MongoDB Connection established'))
.catch((err) => console.log('Error connecting MongoDB database due to: ', err));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Bodyparser
app.use(express.urlencoded({ extended: false }));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
const PORT = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(cors());
app.route('/vessels/all').get(vesselController.getBaseAll);
app.route('vessels/:id/track').get(vesselController.getCurrent);
app.route('/vessels').get(vesselController.getHistory);
app.listen(PORT, console.log(`Server started on port ${PORT}`));
module.exports = app;
VesselController.js
const Vessels = require('../models/Vessels');
const Positions = require('../models/Positions');
const Compnanies = require('../models/Companies');
exports.getBaseAll = (req, res) => {
Promise.all([
Compnanies.find(),
Vessels.find(),
Positions.aggregate([
{
$sort: {
date: -1
}
},
{
$group: {
_id: '$callsign',
details: {
$push: '$$ROOT'
}
}
},
{
$replaceRoot: {
newRoot: {
$arrayElemAt: [ '$details', 0 ]
}
}
}
])
])
.then(([ companies, vessels, positions ]) => {
// apply vessels detail table as join:
positions.forEach((pos) => {
vessels.forEach((ves) => {
if (pos.callsign == ves.callsign) {
p._detail = ves;
}
});
companies.forEach((com) => {
if (p._detail.company == com.number) {
p._detail = com;
}
});
});
res.status(200).json(positions);
})
.catch((err) => {
return res.status(500).send(err);
});
};
exports.getHistory = (req, res) => {
var id = req.param.id;
Positions.find(
{
callsign: id,
date: {
$gte: new Date(Date.now() - 1000 * 60 * 60 * 24)
}
},
(err, task) => {
if (err) {
return res.status(500).send(err);
}
res.status(200).json(task);
}
);
};
exports.getCurrent = (req, res) => {
var currentPos = Positions.find({
date: {
$gte: new Date(Date.now() - 1000 * 60 * 60)
}
});
currentPos.exec((err, task) => {
if (err) {
return res.status(500).send(err);
}
res.status(200).json(task);
});
};
我不确定问题是否出在我试图连接到特定数据库上。按下图所示连接到我的应用程序并复制/粘贴密钥后:
mongodb+srv://<username>:<password>@vessel-tracker-cluster-x2lpw.mongodb.net/test?retryWrites=true&w=majority
以下是我的cluser的组织方式:
访问集合后,您可以看到数据库的结构:
我为解决该问题所做的事情:
我遇到并分析解决该问题的帖子是:
1)This很有用,但我无法解决问题。
2)我使用了this other source,但问题仍然存在。
3)This one也很有用,但是我的问题仍然存在,并且
MongoDB
无法正确连接感谢您指出正确的方向来解决此问题。
最佳答案
从堆栈跟踪中可以看出,app.js:77:27中存在错误:
app.route('/ vessels / all')。get(vesselController.getBaseAll);
尽管我已经执行了您的代码并且运行良好,但是我想向您提出以下建议:
1)在您的VesselController.js中尝试用exports
替换module.exports
;
2)尝试调试app.js,看看vesselController.getBaseAll
/ vesselController.getCurrent
/ vesselController.getHistory
返回什么:
console.log(vesselController.getBaseAll); //应该是[Function]
关于javascript - 错误连接MongoDB:错误:Route.get()需要回调函数,但得到了[对象未定义],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60155838/