简体   繁体   English

错误连接 MongoDB:错误:Route.get() 需要一个回调函数,但得到一个 [object Undefined]

[英]Error connection MongoDB: Error: Route.get() requires a callback function but got a [object Undefined]

I have been trying to connect my application to MongoDB using express but without success.我一直在尝试使用express将我的应用程序连接到MongoDB但没有成功。 Below the most important part of the code:下面是代码最重要的部分:

app.js :应用程序.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容器控制器.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);
    });
};

I am not sure if the problem is due to the fact that I am trying to connect to a specific database.我不确定问题是否是由于我正在尝试连接到特定数据库。 After hitting connect to my application as shown below and copy/paste the key:按如下所示连接到我的应用程序并复制/粘贴密钥后:

联系

mongodb+srv://<username>:<password>@vessel-tracker-cluster-x2lpw.mongodb.net/test?retryWrites=true&w=majority

Below is how my cluser is organized:以下是我的集群的组织方式:

簇

And after accessing the collections you can see how the database is structured:访问集合后,您可以看到数据库的结构:

D b

What I have done to solve the problem:为解决问题所做的工作

Posts that I came across and analyzed to solve the problem were:我遇到并分析解决问题的帖子是:

1) This was useful but I could not solve the problem. 1) 很有用,但我无法解决问题。

2) I used this other source but problem still stays. 2)我使用了其他来源,但问题仍然存在。

3) This one was also useful but my problem still stay and MongoDB is not properly connecting 3) 这个也很有用,但我的问题仍然存在, MongoDB没有正确连接

Thanks for pointing in the right direction for solving this problem.感谢您指出解决此问题的正确方向。

As I see from the stack trace there's an error in app.js:77:27:正如我从堆栈跟踪中看到的那样,app.js:77:27 中有一个错误:

app.route('/vessels/all').get(vesselController.getBaseAll); app.route('/vessels/all').get(vesselController.getBaseAll);

Though I've executed your code and it worked fine I would like to propose you the following:尽管我已经执行了您的代码并且运行良好,但我想向您提出以下建议:

1) Try to substitute exports with module.exports in your VesselController.js; 1) 尝试在您的 VesselController.js 中用module.exports替换exports

2) Try to debug app.js and see what vesselController.getBaseAll / vesselController.getCurrent / vesselController.getHistory returns: 2)尝试调试app.js,看看vesselController.getBaseAll / vesselController.getCurrent / vesselController.getHistory返回什么:

console.log(vesselController.getBaseAll); console.log(vesselController.getBaseAll); // should be [Function] // 应该是 [Function]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:Route.get()需要回调函数,但得到了一个[object Undefined] - Error: Route.get() requires callback functions but got a [object Undefined] 错误:Route.get()需要回调函数,但得到了一个[object Undefined] NODE.JS + SQL - Error: Route.get() requires a callback function but got a [object Undefined] NODE.JS + SQL 错误:Route.get() 需要回调 function 但在使用导入的 function 时得到 [object Undefined] - Error: Route.get() requires a callback function but got a [object Undefined] while using imported function 错误:Route.get() 需要一个回调函数,但在 app.js 中得到一个 [object Undefined] - Error: Route.get() requires a callback function but got a [object Undefined] at app.js 节点服务器错误:Route.get() 需要回调 function 但得到了 [object Undefined] - node server Error: Route.get() requires a callback function but got a [object Undefined] “错误:Route.get() 需要回调 function 但得到 [object Undefined]” 进行多次导出时 - “Error: Route.get() requires a callback function but got a [object Undefined]” when doing multiple exporting Express 应用程序的 Route.get() 需要回调函数,但出现 [object Undefined] 错误 - Route.get() for express app requires a callback function but got a [object Undefined] error 错误:Route.get() 需要回调 function 但在 Node.js 中得到了一个 [object Undefined] - Error: Route.get() requires a callback function but got a [object Undefined] in Node.js 节点:Route.get() 需要一个回调函数,但得到了一个 [object Undefined] - Node: Route.get() requires a callback function but got a [object Undefined] Node.js错误:Route.get()需要回调函数,但是得到了[object Undefined] - Node.js Error: Route.get() requires callback functions but got a [object Undefined]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM