PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 21, 2022

[FIXED] Why node.js always says I'm connected to my MongoDB even if the "URI" is fake or wrong?

 April 21, 2022     connection, mongodb, mongoose, node.js     No comments   

Issue

I'm testing mongoDB connection in node.js with mongoose. I follow the official guide of mongoose and when I try to connect like they said, mongoose always says I'm connected even if the URI given is fake or wrong. Is my connection trying correct ?

I want to connect my app to a database called 'technicaltest'.

My code:

const mongoose = require('mongoose');

const db = mongoose.createConnection('mongodb://localhost/technicaltest', {useNewUrlParser: true});

db.on('connected', () => {
    console.log('Connected to mongoDB !');
});

db.on('disconnected', () => {
    console.log('Disconnected to mongoDB !');
});

The console ouput:

> set PORT=3001 && node bin/www

Connected to mongoDB !

Same output for this code:

const mongoose = require('mongoose');

const db = mongoose.createConnection('mongodb://localhost/someWeirdyThingsHere', {useNewUrlParser: true});

db.on('connected', () => {
    console.log('Connected to mongoDB !');
});

db.on('disconnected', () => {
    console.log('Disconnected to mongoDB !');
});

I think if mongoose cannot connect to the right database in mongoDB nothing will be prompted in the console... But here... The 'connected' event is call anyway.


Solution

I think you forgot to add the port(27017) to your mongodb connection. It should be

const db = mongoose.createConnection('mongodb://localhost:27017/technicaltest', {useNewUrlParser: true});


Answered By - Spidy
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing