REST API-连接到数据库和服务器-不建议使用URL字符串解析器

时间:2018-09-04 12:56:49

标签: node.js mongodb rest api

我正在尝试使用mongodb创建一个简单的rest API。

我有一个server.js文件

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

const app = express();

app.use(bodyParser.json());

const db = require('./config/keys').mongoURI;

mongoose
    .connect('mongodb://test:test123@ds241012.mlab.com:41012/mern_shopping')
    .then(() => console.log('DB Connected'))
    .catch(err => console.log(err));

const port = process.env.PORT || 5000;

app.listen(port, () => console.log('Server started'));

我正在使用nodemon

运行npm run server时出现以下错误

  

(节点:65209)DeprecationWarning:不建议使用当前URL字符串解析器,并将在以后的版本中将其删除。要使用新的解析器,请将选项{useNewUrlParser:true}传递给MongoClient.connect。

然后我在控制台中出错

  

无法连接到服务器

我该如何解决

更新

使用{useNewUrlParser: true}服务器将启动,但是如果我触摸server.js文件,则会显示此信息。

Server started
{ MongoNetworkError: failed to connect to server [ds241012.mlab.com:41012] on first connect [MongoNetworkError: connection 0 to ds241012.mlab.com:41012 timed out]
    at Pool.<anonymous> (/Users/test/Documents/_Work/cd/React/mern-shopping-list/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> (/Users/test/Documents/_Work/cd/React/mern-shopping-list/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> (/Users/test/Documents/_Work/cd/React/mern-shopping-list/node_modules/mongodb-core/lib/connection/connection.js:257:10)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:106:13)
    at Socket.emit (events.js:208:7)
    at Socket._onTimeout (net.js:420:8)
    at ontimeout (timers.js:482:11)
    at tryOnTimeout (timers.js:317:5)
    at Timer.listOnTimeout (timers.js:277:5)
  name: 'MongoNetworkError',
  errorLabels: [ 'TransientTransactionError' ],
  [Symbol(mongoErrorContextSymbol)]: {} }

0 个答案:

没有答案