1
votes

I am a biginner to nodejs and 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. (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 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 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. 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:10124) [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.

i am trying to build a url shortner. This is the code.

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

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.

1
It looks like mongodb is not running at 127.0.0.1:27017 or localhost:27017nijm
You haven't started your mongodb service... Try to start it with sudo service mongod start if you are using Ubuntu or go to bin folder and type mongo if you are using WindowsAshh

1 Answers

0
votes

You haven't start your mongodb service,

Start it with command: sudo mongod and then try to start your server.