How can I connect without to a distant database (MONGOHQ) without using MongoClient.connect() ?
var db, mongo, server;
mongo = require("mongodb");
server = new mongo.Server("mongodb://login:password#paulo.mongohq.com:10057//appname", 10057, {
auto_reconnect: true
});
db = new mongo.Db("confirmed", server, { safe: true });
the message I get from my server is
[Error: failed to connect to [mongodb://login:password#paulo.mongohq.com:10057//appname:10057]]
Any ideas ?
You want something more like this, where you define the server as a DNS name (no protocol, port, auth or path):
server = new mongo.Server("paulo.mongohq.com", 10057, {
auto_reconnect: true
});
db = new mongo.Db("confirmed", server, { safe: true });
and then once db is defined:
db.open(function(erreur, db) {
db.authenticate('user', 'name', function(err, result) {
//
});
Related
I have created a DocumentDB with SSL enabled and I am using mongodb package using NodeJS to connect this DB using a Bastion Host. The issue is that if I put a hardcoded string inside the MongoClient.connect function, I am able to successfully connect the DB. The hardcoded code would look like as shown below.
let MongoClient = require('mongodb').MongoClient;
let client = MongoClient.connect(
'mongodb://User:PWD#DBURL:27017/DBNAME?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false',
{
tlsCAFile: __dirname + `rds-combined-ca-bundle.pem` //Specify the DocDB; cert
},
function(err, client) {
if(err)
throw err;
console.log("1111111 2222222!!");
//Specify the database to be used
db = client.db('DBNAME');
//Specify the collection to be used
col = db.collection('COLNAME');
console.log("1111111 connected to db!!");
client.close();
});
Now as that's not an ideal situation to put the hardcoded values in the code. I am trying to read the values from environment variables and trying to put the whole URL into a string variable and passing this variable into that function such as shown below.
const DBURL = "mongodb://"+user+":"+pwd+"#"+dbURL+":"+port+"/"+dbName+"?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false";
let client = MongoClient.connect(DBURL,
{
tlsCAFile: __dirname + `rds-combined-ca-bundle.pem` //Specify the DocDB; cert
},
function(err, client) {
Now this one timesout to connect the DB.
Any suggestions on it or should I use any other packages to connect DocumentDB via NodeJS, do let me know.
Something like this works for me:
const { MongoClient } = require('mongodb')
const DOCUMENTDB_CONNECTION_STRING = `mongodb://${process.env.DOCDB_USER}:${process.env.DOCDB_PASS}#${process.env.DOCDB_ENDPOINT}/${process.env.DOCDB_DBNAME}?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false`
const client = MongoClient.connect(
DOCUMENTDB_CONNECTION_STRING, {
tlsCAFile: `rds-combined-ca-bundle.pem` //Specify the DocDB cert
},
function(err, client) {
Is this what you are looking for?
I am using the sails js framework. I have a service in which I am using a query like this:
Users.query('select * from remotedb', (err, results) => {
//Do something with results
});
I have to use this query from remote database. How to achieve this?
You will first need to create a connection object. I wrote a snippet which will get this done. Assuming that we use MSSQL server:
let sql = require('mssql');
// Make sure that you add 'mssql' node module in your package.json file
// https://www.npmjs.com/package/mssql
// This is Microsoft SQL Server client for Node.js
let sqlConnectionConfig = {
server: 'Your Database Server URL',
user: 'Your Username',
password: 'Your Password',
database: 'Your Database Name',
};
let connection = new sql.Connection(sqlConnectionConfig);
connection.connect()
.then(() => {
new sql.Request(connection)
.query('SELECT * FROM Role')
.then(function (recordset) {
res.send(recordset); // Or do any other fancy stuff
})
.catch((sqlServerError) => res.send(sqlServerError));
})
.catch((connectionError) => res.send(connectionError));
You can change the connection string and driver based on which database you are going to use. Let me know if this worked for you!
I am totally new to node.js and mongoose, how to reconnect mongoose to another remote server ?
At the beginning of the file I have
var mongoose = require('mongoose')
and connected to localhost,
later in code I have
var uristring ='mongodb://remote_server/db';
var mongoOptions = { db: { safe: true } };
// Connect to Database
mongoose.createConnection(uristring, mongoOptions, function (err, res) {
if (err) {
console.log ('ERROR connecting to: remote' + uristring + '. ' + err);
} else {
console.log ('Successfully connected to: remote' + uristring);
}
});
and I always get Successfully connected to: remote but when I bellow that print look for document by id I get always from local database(I have schema imported like require Person = mongoose.model('Person');).
How to reconnect to remote if I already have connection to local.
There are two ways of initializate a connection in mongoose:
Using the default connection "object"
Creating a connection from the dust
Here you are creating a connection, but using a model from another. Models are tied to databases (normal databases, replica sets or clusters) so you're not accesing to the correct host.
You must use the default connection (using mongoose.connect instead of mongoose.createConnection) or create a model in that new connection you are using. In your example:
var uristring ='mongodb://remote_server/db';
var mongoOptions = { db: { safe: true } };
// Connect to Database
var newConnection = mongoose.createConnection(uristring, mongoOptions);
newConnection.model(/*whatever*/);
mongoose.model wires to mongoose.connection. That is not the new connection you have created.
I've been looking for a way to do various operations on a mongo database, depending on which route a user connects to on my website. So doing a html-post to www.mysite.com/data would add info to a mongo DB, and doing a html-get at the same url would get data from the same database. I managed to solve that, but everytime I turn on my server with the website I get 5 connections registred at the mongo database. Why is this, and is it bad?
My code:
I'm runing this code in mongo.js:
var mongodb = require('mongodb');
module.exports.init = function (callback) {
var server = new mongodb.Server("127.0.0.1", 27017, {});
new mongodb.Db('test', server, {w: 1}).open(function (error, client) {
//export the client and maybe some collections as a shortcut
module.exports.client = client;
module.exports.myCollection = new mongodb.Collection(client, 'myCollection');
callback(error);
});
};
I initialize everything running (app.js):
/express set-up/
var mongo = require('./mongo.js');
/.../
mongo.init(function (error) {
if (error)
throw error;
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode",3000,
app.settings.env);
});
});
And, for example, the post looks like (still app.js):
app.post('/App', function(req, res) {
users = users.concat(req.body);
res.redirect('/App');
//Add user to MongoDB
mongo.myCollection.insert({name: req.body.name, car: req.body.car, website: req.body.website, phone: req.body.phone}, {safe:true}, function(err, objects) {
if (err)
console.warn(err.message);
});
Pretty sure my redirect isn't working as I want it too here, but that's another issue.
Anny suggestions on why I get five connects every time I start the server?
The five connections are because that is the default poolSize (5). You can adjust it, as outlined in the server options docs - it also mentions the default.
Code:
var Db = require('mongodb').Db,
Server = require('mongodb').Server,
Client = new Db('test', new Server('127.0.0.1', 52235, {}))
In Function:
...
Client.open(function(err, pClient) {
Client.collection('test_insert', function(err, collection){
collection.find().toArray(function(err, results) {
console.log(results);
});
});
// etc.
});
This shows error: Cannot read property 'arbiterOnly' of undefined
can you help me?
This error occurs because it couldn't connect to the server and so the configuration information wasn't properly received. Probably you are using the wrong port: try 27017.