连接到databse时出错-nodejs和mongodb

时间:2018-07-07 14:38:38

标签: node.js mongodb

我是nodejs和mongodb的重要人物。尝试连接数据库时遇到以下错误:

(节点:10124)UnhandledPromiseRejectionWarning:MongoNetworkError:首次连接时无法连接到服务器[127.0.0.1:27017] [MongoNetworkError:connect ECONNREFUSED 127.0.0.1:27017]     在游泳池。 (E:\ node js工作区\ URL-Shortner \ server \ node_modules \ mongodb-core \ lib \ topologies \ server.js:562:11)     在emitOne上(events.js:116:13)     在Pool.emit(events.js:211:7)     在连接。 (E:\ node js工作区\ URL-Shortner \ server \ node_modules \ mongodb-core \ lib \ connection \ pool.js:316:12)     在Object.onceWrapper(events.js:317:30)     在emitTwo(events.js:126:13)     在Connection.emit(events.js:214:7)     在套接字。 (E:\ node js工作区\ URL-Shortner \ server \ node_modules \ mongodb-core \ lib \ connection \ connection.js:245:50)     在Object.onceWrapper(events.js:315:30)     在emitOne上(events.js:116:13)     在Socket.emit(events.js:211:7)     在emitErrorNT上(internal / streams / destroy.js:64:8)     在_combinedTickCallback(内部/进程/next_tick.js:138:11)     在process._tickCallback(内部/进程/next_tick.js:180:9) (节点:10124)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。引发此错误的原因可能是抛出了一个没有catch块的异步函数,或者是拒绝了一个.catch()无法处理的承诺。 (拒绝ID:1) (节点:10124)[DEP0018] DeprecationWarning:已弃用未处理的承诺拒绝。将来,未处理的承诺拒绝将以非零退出代码终止Node.js进程。

我正在尝试构建网址缩短器。这是代码。

index.js-

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const mongoURI = "mongodb://localhost/url-shortner";
const connectOptions={
keepAlive: true,
reconnectTries: Number.MAX_VALUE
};
mongoose.connect(mongoURI,connectOptions,(err,db)=>{
if(err) console.log('Error',err);
console.log('Connected to MongoDB');
});
const app = express();
require("./models/UrlShorten");
app.use(bodyParser.json());
require("./routes/urlshorten")(app);
const PORT = 7000;
//Start server on Port 7000
  app.listen(PORT, () => {
console.log(`Server started on port`, PORT);
});

urlshorten.js-

const mongoose = require("mongoose");
const validUrl = require("valid-url");
const UrlShorten = mongoose.model("UrlShorten");
const shortid = require("shortid");
const errorUrl='http://localhost/error';
module.exports = app => {
app.get("/api/item/:code", async (req, res) => {
const urlCode = req.params.code;
const item = await UrlShorten.findOne({ urlCode: urlCode });
if (item) {
  return res.redirect(item.originalUrl);
 } else {
   return res.redirect(errorUrl);
 }
});
 app.post("/api/item", async (req, res) => {
 const { originalUrl, shortBaseUrl } = req.body;
 if (validUrl.isUri(shortBaseUrl)) {
 } else {
   return res
     .status(401)
     .json(
       "Invalid Base Url"
     );
 }
 const urlCode = shortid.generate();
 const updatedAt = new Date();
 if (validUrl.isUri(originalUrl)) {
   try {
     const item = await UrlShorten.findOne({ originalUrl: originalUrl });
     if (item) {
       res.status(200).json(item);
     } else {
       shortUrl = shortBaseUrl + "/" + urlCode;
      // console.log("Shorturl: "+shortUrl);
        const item = new UrlShorten({
         originalUrl,
         shortUrl,
         urlCode,
         updatedAt
       });
       await item.save();
       res.status(200).json(item);
     }
    } catch (err) {
    res.status(401).json("Invalid User Id");
   }
  } else {
   return res
     .status(401)
     .json(
       "Invalid Original Url"
     );
 }
});
};

这是架构:

Schema({
originalUrl: String,
urlCode: String,
shortUrl: String,
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }

});

谢谢。

1 个答案:

答案 0 :(得分:0)

您尚未启动mongodb服务,

使用命令sudo mongod启动它,然后尝试启动服务器。