Local Node.js script not connecting to mongoDB database - node.js

I setup a MongoLab MongoDB database through Heroku and am able to connect to it in the shell by issuing the below command:
mongo ds061701.mongolab.com:61701/heroku_app35721468 -u <dbuser> -p <dbpassword>
I'm using Node.js and Express and wrote the following code in a script.js file, which sits in the same directory as a node_modules folder containing mongoose.
var mongoose = require('mongoose');
mongoose.connect('mongodb://<dbuser>:<dbpassword>#ds061701.mongolab.com:61701/heroku_app35721468');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
db.once('open', function(){
console.log('db connected');
});
When navigate to the directory of this script in Terminal and type node script.js, I get the following error message:
dyld: lazy symbol binding failed: Symbol not found: _node_module_register
Referenced from: /Users/Jack/Documents/node-express-101/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/build/Release/bson.node
Expected in: dynamic lookup
dyld: Symbol not found: _node_module_register
Referenced from: /Users/Jack/Documents/node-express-101/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/build/Release/bson.node
Expected in: dynamic lookup
Trace/BPT trap: 5
What am I doing wrong here and how can I connect to my MongoDB database hosted on MongoLab with mongoose?

Referring to comments from OP's original question: the solution was the original dependency install did not complete successfully. Reinstalling solved it.

That error will be thrown when you have installed modules (that require compilation) with Node 0.12, but subsequently try to run those modules with an older Node version (like 0.10).

Related

How to resolve the `at Module._resolveFilename (node:internal/modules/cjs/loader:1039:15)` and server selection error

I have been trying to connect database locally to mongodb using nodejs but there are some errors i'm facing some errors while doing that.
In my main folder there is only one connection file named as db.js and other files are package.json and node_modules. This is error I got after running the node db.js at particular location I have installed mongoose also using npm command.
and after using the command node --trace-deprecation I got the following error log.
Here's the code of db.js:-
const mongoose=require('mongoose');
mongoose.connect('mongodb://localhost:27017').then(()=>{
console.log(`conncn established!!\n`);
}).catch((err)=>{
console.log('no connection',err);
})
// module.exports=mongoose;
// "mongodb://localhost:27017/Blogs_db -->it is the connection string for Blogs_db tried to but this //string also but it is not working
I have checked whether my server is running or not and tried to make the new folder and to follow the process again but it still shows the connection error
Go the answer and it is simple just to replace the local host in the connection string with 0.0.0.0 and it worked[Heres the output after replacing the localhost in above code with 0.0.0.0]

Authentication problem with connecting to mongodb Atlas

What I want to accomplish is probably the simplest thing ever. I just want to connect to mongodb atlas free tier M0 in nodejs using mongodb driver. I already have created a free account and cluster.
Here is my simple code:
const mongoclient = require('mongodb').MongoClient;
const URI = 'mongodb+srv://mohammed:mypassword#lebran-0qf7m.gcp.mongodb.net/test?retryWrites=true';
mongoclient.connect(URI, { useNewUrlParser: true }, (err, client) => {
if(err) throw err;
console.log('mongodb connected');
db = client.db('mern');
})
Here is what happens when I run the file:
Mohammeds-MacBook-Pro:mern ahmed$ node server.js
/Users/ahmed/Projects/mern/server.js:13
if(err) throw err;
^
Error: queryTxt ESERVFAIL lebran-0qf7m.gcp.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:199:19)
I also tried mongo shell with the following command:
mongo "mongodb+srv://lebran-0qf7m.gcp.mongodb.net/mern" --username mohammed
here is the output I get:
MongoDB shell version v4.0.6
Enter password:
connecting to: mongodb://lebran-shard-00-00-0qf7m.gcp.mongodb.net.:27017,lebran-shard-00-01-0qf7m.gcp.mongodb.net.:27017,lebran-shard-00-02-0qf7m.gcp.mongodb.net.:27017/mern?gssapiServiceName=mongodb&ssl=true
2019-02-20T22:48:57.232+0300 E QUERY [js] Error: Authentication failed. :
connect#src/mongo/shell/mongo.js:343:13
#(connect):1:6
exception: connect failed
I am sure I enter my password right. I have changed several ones and none of them work. I have my IP listed as white list. I also have an admin account. All the prerequisites I can think of.
I am able to connect to the local server but not to the Atlas. This really beginning to drive me crazy.
Any help is greatly appreciated...
**UPDATE:
I just deployed my app to heroku and you know what? It connects!! I could not get it to connect using my computer though. So probably it has to do something with my location or my connection, probably the location.

mongoose not connecting to localhost

I seem to have issues when trying to create a mongoose connection. I am following a book published in 2014 so my immediate response was to check the mongoose docs but they agree that the book gives the correct format. Below is my connection:
var dbURI = 'mongodb://localhost/Loc8r';
mongoose.connect(dbURI);
As soon as I add these lines, I get the following error:
Mongoose connection error: mongodb://127.0.0.1/Loc8r
(node:743) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
(node:743) [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.
If I remove the connection, I have no errors...but that would defeat the purpose of trying to connect to a DB. I also tried substituting localhost in the URI for 127.0.0.1 which is known to solve some issues but I had no luck there either. I am running the localhost on a simple $nodemon command via terminal and nothing else.
Useful info:
MongoDB v3.6.3
Mongoose v5.0.10
Express v4.15.5
Node v8.9.4
Help would be appreciated.
Thanks.
try this way
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
db.close();
});
You are going on the right path but you forgot to put the port on which MongoDB runs,
MongoDB runs on the port 27017
Do not forget to start MongoDB server, If you are on mac open terminal and enter mongod and it will start your MongoDB server then run your code it will work fine.
var dbURI = 'mongodb://localhost:27017/Loc8r';
mongoose.connect(dbURI);
mongoose.connection.on("connected", () => {
console.log("Connected to database");
});
mongoose.connection.on("error", (err) => {
console.log("Database error:" + err);
});
I apologise for this as I was able to find the solution myself but I guess this may help others some day.
The fault lay with the fact that I only installed MongoDB via Homebrew and I stopped as soon as MongoDB was literally "installed" and considered MongoDB to be "installed". I went back to look at how MongoDB should properly be installed and I noticed that I did not make the directory /data/db and give it its permissions which was an important step.
Once I did this, I ran mongod globally, and nodemon on a separate terminal, locally at the root of the app and it worked completely fine and got a successful message in the console. Every time I tried to connect, it was searching for /data/db which it obviously could not find as I had not made it. But I would not have came to this conclusion if Nikhil had not mentioned running mongod.
To summarise, ensure you follow all installing steps in future.

node js mongoose mongoDB

Using phpstorm, trying to get mongoDB server up and running using nodeJS, i have mongo installed and have created the required folders on the c drive to store database, proceeded by going to command prompt and entering mongod, to get mongo db running....
checked npm ls,mongoose and mongo are listed fine, and are also present in my package json file.
when i try to run the index file from commmand prompt 'node index.js' i get the following error, see pic for details, i have included, the code used for setting up mongo... i have disable mongoserver from phpstorm repository, and use the one from the mongodb website
"mongodb": "3.0.0-rc0",
"mongoose": "^5.0.0-rc2",
var mongoose =require('mongoose');
//connect to mongoose
mongoose.connect('mongodb://localhost/quaver');
mongoose.connection.once('open', function(){
console.log('connection has been made , and is running')
});
mongoose.on('error', function(error){
console.log('Connection error',error);
});
error sorted by omitting the following lines from the semver.js file, in the node modules folder in the current project
line 203,204
//re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
//nodevar comparatorTrimReplace = '$a$2$3';
and line 232
// re[i] = new RegExp(src[i]);
mongoose now up and running

Cannot connect to mongo on heroku due to missing replicaset parameter

I have a node.js app running on heroku. I am trying to update my mongodb module to "~2.0.3". In my local dev. environment everything is working fine. However, when I deploy the to Heroku I get a "replicaSet parameter must be set" error which did not fire with earlier version of the mongodb module. I am not how to go about it. In particular, I have no idea where can I find the name of that replicaSet.
Here's a transcript of a node REPL session showing the problem:
$ heroku run node --app my-app
Running `node` attached to terminal... up, run.8299
>var mongo = require('mongodb');
undefined
> var a = {}
undefined
> process.env.MONGOLAB_URI
'mongodb://UUUUU:PPPPP.mongolab.com:45970/heroku_appNNNNNNN'
> mongo.MongoClient.connect(process.env.MONGOLAB_URI, function (err, db) {
a.err = err; a.db = db; console.log('CALLED'); });
undefined
> CALLED
undefined
> a
{ err:
{ [MongoError: replicaSet parameter must be set]
name: 'MongoError',
message: 'replicaSet parameter must be set' },
db: null }
>
One more thing: when I access the DB through the web interface I see only two system collections: system.indexes and system.users. To the best of my understanding this suggests that my DB is not part of a replicaSet which makes the whole thing weird.
This is indeed a problem in 2.0.3. It was solved in 2.0.4 by this pull request.
Bottom line: If you encounter "replicaSet parameter must be set" error in 2.0.3, upgrade to 2.0.4.

Resources