简体   繁体   English

连接到数据库时出错-Node.js和MongoDB

[英]Error while connecting to databse - nodejs and mongodb

I am a biginner to nodejs and mongodb. 我是nodejs和mongodb的重要人物。 I encountered the following error while trying to connect to database: 尝试连接数据库时遇到以下错误:

(node:10124) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] at Pool. (节点:10124)UnhandledPromiseRejectionWarning:MongoNetworkError:首次在Pool上连接[MongoNetworkError:connect ECONNREFUSED 127.0.0.1:27017]时,无法连接到服务器[127.0.0.1:27017]。 (E:\\node js workspace\\URL-Shortner\\server\\node_modules\\mongodb-core\\lib\\topologies\\server.js:562:11) at emitOne (events.js:116:13) at Pool.emit (events.js:211:7) at Connection. (E:\\ node js工作区\\ URL-Shortner \\ server \\ node_modules \\ mongodb-core \\ lib \\ topologies \\ server.js:562:11)在Pool.emit(events)的emitOne(events.js:116:13)。 js:211:7)。 (E:\\node js workspace\\URL-Shortner\\server\\node_modules\\mongodb-core\\lib\\connection\\pool.js:316:12) at Object.onceWrapper (events.js:317:30) at emitTwo (events.js:126:13) at Connection.emit (events.js:214:7) at Socket. (E:\\ node js工作区\\ URL-Shortner \\ server \\ node_modules \\ mongodb-core \\ lib \\ connection \\ pool.js:316:12)位于atmitTwo(events.js:317:30)。 js:126:13),位于Socket的Connection.emit(events.js:214:7)。 (E:\\node js workspace\\URL-Shortner\\server\\node_modules\\mongodb-core\\lib\\connection\\connection.js:245: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:10124) UnhandledPromiseRejectionWarning: Unhandled promise rejection. (E:\\ node js工作区\\ URL-Shortner \\ server \\ node_modules \\ mongodb-core \\ lib \\ connection \\ connection.js:245:50)在emitOne(事件.js:315:30)。 js:116:13)出现在Socket.emit(events.js:211:7)出现在_combinedTickCallback(internal / process / next_tick.js:138:11)出现在emitErrorNT(internal / streams / destroy.js:64:8)的地方process._tickCallback(内部/进程/next_tick.js:180:9)(节点:10124)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。 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(). 引发此错误的原因可能是抛出了一个没有catch块的异步函数,或者是拒绝了一个没有使用.catch()处理的promise。 (rejection id: 1) (node:10124) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. (拒绝ID:1)(节点:10124)[DEP0018] DeprecationWarning:已弃用未处理的承诺拒绝。 In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 将来,未处理的承诺拒绝将以非零退出代码终止Node.js进程。

i am trying to build a url shortner. 我正在尝试构建一个URL缩短器。 This is the code. 这是代码。

index.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- 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"
     );
 }
});
};

This is the schema: 这是模式:

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

}); });

Thank you. 谢谢。

You haven't start your mongodb service, 您尚未启动mongodb服务,

Start it with command: sudo mongod and then try to start your server. 使用以下命令启动它: sudo mongod ,然后尝试启动服务器。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM