Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to mongoDB compass with Node.js

I am trying to send data from node.js to a mongoDB compass server. I have created a MongoDB cluster and downloaded Compass. I can connect Compass to the cluster it all works fine.

However when I try to connect my Node.js server to Compass I get an error, Below is my node code.

const express = require('express');

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');



const app = express();

// Connect to mongodb
// Connection URL

const url = "mongodb://tfi-mfgbt.mongodb.net/test" ;

// Database Name
const dbName = 'TFI';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});


const port = 5000;

app.listen(port, () => {
    console.log(`Server started on port ${port}`);
});

One I run Node app.js in terminal I get

MongoClient.connect.                                                                                                                                                              
Server started on port 5000                                                                                                                                                       
F:\code\vidjot\node_modules\mongodb\lib\operations\mongo_client_ops.js:439                                                                                                        
      throw err;                                                                                                                                                                  
      ^                                                                                                                                                                           

AssertionError [ERR_ASSERTION]: null == 'MongoNetworkError: failed to connect to server [tfi-mfgbt.mongodb.net:27017] on first connect [MongoNetworkError: getaddrinfo E          
    at F:\code\vidjot\app.js:20:10                                                                                                                                                
    at err (F:\code\vidjot\node_modules\mongodb\lib\utils.js:415:14)                                                                                                              
    at executeCallback (F:\code\vidjot\node_modules\mongodb\lib\utils.js:404:25)                                                                                                  
    at err (F:\code\vidjot\node_modules\mongodb\lib\operations\mongo_client_ops.js:284:21)                                                                                        
    at connectCallback (F:\code\vidjot\node_modules\mongodb\lib\operations\mongo_client_ops.js:240:5)                                                                             
    at process.nextTick (F:\code\vidjot\node_modules\mongodb\lib\operations\mongo_client_ops.js:436:7)                                                                            
    at _combinedTickCallback (internal/process/next_tick.js:131:7)                                                                                                                
    at process._tickCallback (internal/process/next_tick.js:180:9)                                                                                                                
[nodemon] app crashed - waiting for file changes before starting...                       

The hostname "mongodb://tfi-mfgbt.mongodb.net/test" is the host name of my Compass session. As seen here

like image 367
Matt Avatar asked Aug 08 '18 12:08

Matt


1 Answers

To connect with Mongo I use this lines of code:

    var mongoUrl = '"mongodb://tfi-mfgbt.mongodb.net/test"'
    var mongoose = require('mongoose')
    // updated 2021
    mongoose.Promise = global.Promise;
    mongoose.set('useNewUrlParser', true);
    mongoose.set('useFindAndModify', false);
    mongoose.set('useCreateIndex', true)
    
    mongoose.connect(mongoUrl, { useUnifiedTopology: true })
    .then(() => { log('Connected to MongoDB: %s \n ', mongoUrl) }) 
    .catch((err) => { error('MongoDB connection error: %s \n', err); })

    // Old connection
    //mongoose.connect(mongoUrl, { useMongoClient: true })
    //mongoose.connection.on('error', err => debug('MongoDB connection error: ${err}'));

This should work for you!

And to query:

mySchema.find({},function(err, docs){... My code ...})
like image 138
Sergi Nadal Avatar answered Oct 29 '22 16:10

Sergi Nadal