0

I'm trying to create a web page that will pull data from MongoDB server.

I tried to use node js driver, but it regularly throwing this error:

enter image description here

this is my mongo.js script:

require(['mongodb'], function(mongodb) {
    mongodb.MongoClient.connect("mongodb://x.x.x.x:27017", function (err, client) {
        console.log("Connected successfully to server");
    });
});

The method connect is not working for me (it throws the error). I tried to connect in a many different ways.

I placed it in the bottom of the html body.

How can I solve this problem?

Thanks!

Roi Amiel
  • 353
  • 1
  • 3
  • 18
  • Possible duplicate of [Best way to connect to Mongodb using Node](https://stackoverflow.com/questions/38485575/best-way-to-connect-to-mongodb-using-node) – Sumithran Aug 05 '18 at 07:45

2 Answers2

0

There is nothing called mongodb in node, in order to use mongodb in node, you have to use middlewares like mongoclient or mongoose that connect to mongo db.

Syntax :

require('mongodb').MongoClient.connect("mongodb://localhost:27017/mydb",function(err,db){
   if(err)
     throw err;
   console.log("connected successfully");
   db.close();
});

You are using square bracket, that might not including mongodb else if you are sure that your syntax is right, you can check it by following code

let mon = require(['mongodb']);
console.log(mon)

If above two lines doesnot give error, then please ping me I will see more over it but primarily I can see the error while you are calling require(['mongodb']).

Rnayak
  • 96
  • 11
  • also, first check that wether you have included the mongo.js file correctly as resource.js is sending **error 404** – Rnayak Aug 05 '18 at 07:58
  • I tried to use `require` without brackets, but it throws this error: `Module name "MongoDB" has not been loaded yet for context: _. Use require([])`, I also tried mongoose but it gave the same problem. – Roi Amiel Aug 05 '18 at 08:00
  • before requiring it, have you installed **mongoclient** using npm? – Rnayak Aug 05 '18 at 08:02
  • `var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/mydb"; MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("Database created!"); db.close(); });` run the following code and share the output you are getting. – Rnayak Aug 05 '18 at 08:19
  • Module name "mongodb" has not been loaded yet for context: _. Use require([]) – Roi Amiel Aug 05 '18 at 08:27
  • it seems like it can't find some mongodb.js file – Roi Amiel Aug 05 '18 at 08:29
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177432/discussion-between-rnayak-and-roi-amiel). – Rnayak Aug 05 '18 at 08:29
0

use this one

    import MongoClient from 'MongoDB;
//Create a database named "mydb":
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});