i have installed mongodb (1.8.3) on two seperate servers and set them up to use "replica sets" as found here: http://www.mongodb.org/display/DOCS/Replica+Set+Tutorial
everything looks good so far: one server is recognized as primary, one as secondary (when i access them via commandline).
the problem is that i can't connect to the DB using node.js (0.4.10) and mongoose (2.1.0) like this:
var mongo = require('mongoose');
mongo.connectSet('mongodb://host/dbname,mongodb://host2/dbname');
i always get the following error message:
TypeError: Cannot read property 'reconnectWait' of undefined
at new <anonymous> (/var/www/node/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connections/repl_set_servers.js:23:31)
at NativeConnection.doOpenSet (/var/www/node/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:80:18)
at NativeConnection.openSet (/var/www/node/node_modules/mongoose/lib/connection.js:252:8)
at Mongoose.connectSet (/var/www/node/node_modules/mongoose/lib/index.js:116:27)
...
searched around a bit and found a post somewhere saying that i also have to supply the name of the replica set - so i tried this instead:
mongo.connectSet('mongodb://host/dbname,mongodb://host2/dbname', rs_name:"name_replicaset"});
what am i doing wrong here ...?!
ok, there was an error in the https://github.com/christkv/node-mongodb-native module. it's fixed now but not yet pushed to NPM. so for all you guys getting the same error, here is the fix:
https://github.com/christkv/node-mongodb-native/pull/340
after that, you can just say
var mongo = require('mongoose');
mongo.connectSet('mongodb://host:27018/testdb, host2:27017/testdb, host3:27019/testdb', function (err) {
if (err) {
console.log("could not connect to DB: " + err);
}
});
mongo.connection.on('open', function () {
console.log("mongodb connection open");
}
Related
I am using NextJS to build an app. I am using MongoDB via mongoosejs to connect to my database hosted in mongoAtlas.
My database connection file looks like below
import mongoose from "mongoose";
const MONGO_URI =
process.env.NODE_ENV === "development"
? process.env.MONGO_URI_DEVELOPMENT
: process.env.MONGO_URI_PRODUCTION;
console.log(`Connecting to ${MONGO_URI}`);
const database_connection = async () => {
if (global.connection?.isConnected) {
console.log("reusing database connection")
return;
}
const database = await mongoose.connect(MONGO_URI, {
authSource: "admin",
useNewUrlParser: true
});
global.connection = { isConnected: database.connections[0].readyState }
console.log("new database connection created")
};
export default database_connection;
I have seen this MongoDB developer community thread and this GitHub thread.
The problem seems to happen only in dev mode(when you run yarn run dev). In the production version hosted on Vercel there seems to be no issue. I understand that in dev mode the server is restarted every time a change is saved so to cache a connection you need to use as global variable. As you can see above, I have done exactly that. The server even logs: reusing database connection, then in mongoAtlas it shows like 10 more connections opened.
How can I solve this issue or what am I doing wrong?
I have been trying to connect to Atlas using the university.mongodb.com connection string:
mongodb+srv://m001-student:m001-mongodb-basics#cluster0-jxeqq.mongodb.net/test
But the compass GUI gives the following error:
queryTxt ETIMEOUT cluster-0-jxeqq.mongodb.net
I created my own cluster and tried again. But unfortunately, the same error showed up. I tried to write a JavaSript code as (the angular placeholders had the actual values in them):
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<user>:<password>#cluster0.amffz.gcp.mongodb.net/<dbname>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
if (err) return console.log(err);
const collection = client.db("test").collection("collection-1");
client.close();
});
...which gave me this error:
Error: queryTxt ETIMEOUT cluster0.amffz.gcp.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:202:19) {
errno: undefined,
code: 'ETIMEOUT',
syscall: 'queryTxt',
hostname: 'cluster0.amffz.gcp.mongodb.net'
}
In Atlas, I enabled the Network Access in the Security option to :
0.0.0.0/0
I disabled my firewall just to be sure that the connection is not being blocked:
sudo ufw disable
But nothing seems to work.
Any help?
[Edit]
System Config: Ubuntu 20.04 LTS
I figured out that the machine which I was using had some problem with the connectivity.
I figured out the way to solve this. I uninstalled MongoDB. It seemed like it had some configuration issues.
I removed mongodb and mongoose npm packages as well.
Re-installed everything. And viola, it got connected!
I am new to mongodb and mongoose. I used the below code from internet. I never created the database MEANSTACK which i am referring below. When saving the record it never complained that DB or collection does not exist like it used to happen in MYSQL. How do i make sure that DB or collection exists before doing any operation and its not created automatically.
var mongoose = require( 'mongoose' );
var dbURI = 'mongodb://localhost/MEANSTACK';
mongoose.connect(dbURI);
mongoose.connection.on('connected', function () {
console.log(chalk.green('Mongoose connected to ' + dbURI));
});
mongoose.connection.on('error',function (err) {
console.log(chalk.red('Mongoose connection error: ' + err));
});
mongoose.connection.on('disconnected', function () {
console.log(chalk.red('Mongoose disconnected'));
});
Sry for writing my note as an answer. I can't write comments because my repo is below 50. When you run your server and it runs with no mistakes, that means your database var dbURI = 'mongodb://localhost/MEANSTACK' exists or at least your mongodb server is accessible. Otherwise you would get an error:
failed to connect to server [localhost:27017] on first connect
And additionally mongoose creates a db if it doesn't exist on server run, so it do the check you need on server run like "out of the box"
Quite simply, I'm trying to connect to a MongoDB via Node.js:
Db = require('../v2/node_modules/mongodb').Db
Connection = require('../v2/node_modules/mongodb').Connection
Server = require('../v2/node_modules/mongodb').Server
console.log "before"
DbServer = new Server("localhost", 27017, {})
db = new Db("twitter", DbServer, {native_parser:true})
console.log "after"
return
That's my code and it's as simple as it gets. My output, however, seems to stop at the db = new Db... line.
It never gets to the after. It doesn't give an error either. I know I have a DB running and when I fire up MongoHub, it's there along with the twitter database
Just remove the native_parser=true would be ok
Native bson parser not compiled, please compile or avoid using native_parser=true
I've come across a node chat example on github, When I try to run it, I see the following error:
Error connecting to mongo perhaps it isn't running ?
I've installed mongo 0.9.2, nodejs 5.2 pre, npm 3.0 and other dependencies. The example can be found here: https://github.com/gregstewart/chat.io
I can not determine whether if the example not really works or I didn't run it right. Please help.
Did you install and start mongo-db on your system? This error is mostly because of a missing mongo instance running on the local machine.
Check out the follwing code excerpts from chat.io.
main.js:
/**
* Configure the user provider (mongodB connection for user data storage)
*/
var userProvider = new UserProvider('localhost', 27017);
Creates a new UserProvider object using host and port for database (localhost:27017, mongo-db default).
UserProvider.js:
UserProvider = function(host, port) {
this.db = new mongo.Db('node-mongo-chat', new Server(host, port, {auto_reconnect: true}, {}));
this.db.addListener('error', function(error) {
console.log('Error connecting to mongo -- perhaps it isn\'t running?');
});
this.db.open(function() {
});
};
Opening the connection to the server, printing out an error on failure (the error you mentioned above).
Consider reading up on the mongo-db docs concerning installation and setup here