MongoDB UnhandledPromiseRejection警告错误

时间:2018-09-15 14:19:48

标签: node.js mongodb mongoose

启动节点服务器时出现此错误;我在Windows中使用Git Bash。

(node:1636) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
        at Pool.<anonymous> (C:\Users\nikac\Desktop\js\myapp\node_modules\mongodb-core\lib\topologies\server.js:564:11)
        at emitOne (events.js:116:13)
        at Pool.emit (events.js:211:7)
        at Connection.<anonymous> (C:\Users\nikac\Desktop\js\myapp\node_modules\mongodb-core\lib\connection\pool.js:317:12)
        at Object.onceWrapper (events.js:317:30)
        at emitTwo (events.js:126:13)
        at Connection.emit (events.js:214:7)
        at Socket.<anonymous> (C:\Users\nikac\Desktop\js\myapp\node_modules\mongodb-core\lib\connection\connection.js:246:50)
        at Object.onceWrapper (events.js:315:30)
        at emitOne (events.js:116:13)
        at Socket.emit (events.js:211:7)
        at emitErrorNT (internal/streams/destroy.js:64:8)
        at _combinedTickCallback (internal/process/next_tick.js:138:11)
        at process._tickCallback (internal/process/next_tick.js:180:9)
    (node:1636) 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(). (rejection id: 1)
    (node:1636) [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.

这是我的服务器文件:

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

// set up express app
const app = express();

// connect to mongodb
mongoose.connect('mongodb://localhost:27017/recipego', { useNewUrlParser: true });
mongoose.Promise = global.Promise;

app.use(bodyParser.json());

app.use('/api', require('./routes/api'));

app.listen(8999, function () {
    console.log('App listening on port 8999!')
});

我搜索了很多次,但是没有找到合适的解决方案来帮助我。我尝试了诸如mongo&mongod之类的命令,但它们在我的Git Bash和WinCmd中均不起作用。

1 个答案:

答案 0 :(得分:0)

您的代码似乎没问题。确保mongo正在运行.go到mongo安装目录并找到mongod.exe文件。双击执行它。要在comand行中使用mongod,您必须添加mongod.exe到您的环境变量的路径