Idle Connection Timeout in mongoose - mongodb

Is there any way to set Idle Connection Timeout in mongoose ?
Am trying like the one below.
mongoose.createConnection(IP:port/{server:{"maxIdleTimeMS":1800000}})
But the above code doesn't seem to work. Any help will be appreciated

this option called connectTimeoutMS not maxIdleTimeMS and it is a socket option. this is a sample code that work :
var uri = 'mongodb://localhost/myDb';
var options = { server: { socketOptions: { connectTimeoutMS: 1800000}}};
mongoose.createConnection(uri, options, function (err) {
if (!err){
console.log("Connection successful");}
});
Good luck

Related

MongoDB : Current Topology does not support session

I am learning MEAN Stack development. I am trying to execute a transaction.
Steps I followed :
I start the mongod.exe with flag set to --replSet rs0.
Then I start the Mongo Shell.
Then I write following code.
let session: ClientSession | undefined;
try {
const data = req.body;
console.log(data);
const movie = new Movie({ name: data['name'], cast: data['cast'] });
const conn = await db.connect()
session = await conn.startSession()
session.withTransaction(async () => {
const doc = await movie.save({ session: session, validateBeforeSave: true });
SuccessResponse(res);
res.json(doc);
})
await session.commitTransaction()
session.endSession();
} catch (err) {
console.log(err)
await log(err)
if (session) {
//session.abortTransaction();
session.endSession()
}
ServerError(res);
res.end();
}
But I got follwoing error
MongoError: Current topology does not support sessions
Any help.
It seems like if your connection was on a hold (eg. hitting a break point), MongoError: Current topology does not support sessions gets thrown even though Current topology.. part does not have nothing to do with it. Maybe Session connection timed out. Try again would be more appropriate.
So, if you are sure your setup should support sessions, just try again.

executeAsyncScript timing out

I am trying to execute executeAsyncScript using the following code:
function get(url) {
var callback = function(args) {
console.log(args);
};
var defer = protractor.promise.defer();
browser.executeAsyncScript(function (url, callback) {
console.log("url" + url);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
console.log(xhr.responseText);
callback(xhr.responseText);
defer.fulfill(xhr);
}
}
xhr.open('GET', url , true);
xhr.send();
}, url);
return defer.promise;
};
function setupCommon() {
return get('https://example.com/rest/api/getsomething');
}
var flow = protractor.promise.controlFlow();
flow.execute(setupCommon);
If I execute the code that is passed to executeAsyncScript directly in the browser console then it works. I get the expected output.
console.log("url" + url);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
console.log(xhr.responseText);
callback(xhr.responseText);
defer.fulfill(xhr);
}
}
xhr.open('GET', 'https://example.com/rest/api/getsomething', true);
xhr.send();
But when I execute it using executeAsyncScript, it times out saying:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
The restapi shouldn't have taken much time. I am new to all this. I am not sure what I am doing wrong. Can someone please help me with this.
The default timeout for Jasmine is 2000 milli-seconds which looks inadequate in your case as it looks like you indeed have lot of steps
Check the config file reference doc here for different timeout configurations from the protractor.conf.js
You can either increase the timeout at config level as in below
defaultTimeoutInterval: 60000,
allScriptsTimeout:90000
Or increase it for this test case alone
this.timeout(60000)
The default timeout for a script to be executed is 0ms. In most cases, including the examples below, one must set the script timeout WebDriver.Timeouts.setScriptTimeout(long, java.util.concurrent.TimeUnit) beforehand to a value sufficiently large enough.
Here is link for Java API that provides above information
https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/JavascriptExecutor.html#executeAsyncScript-java.lang.String-java.lang.Object...-

How to connect socket.io and rethinkdb?

After hours of trying. I haven't make it work.
Here's what I have.
var app = require('express')(),
http = require('http').Server(app),
io = require('socket.io')(http),
r = require('rethinkdb');
http.listen(5000);
console.log('Server started on port 5000');
r.connect({db: 'testRealtime'}).then(function(c) {
r.table('messages').insert(
{ message: "realtime" }
)
r.table('messages').changes().run(c)
.then(function(cursor) {
cursor.each(function(err, item) {
io.emit('messages', item)
})
})
})
As you can see on the above example. I am trying to insert a message realtime and look at it on rethinkdb dashboard. But this doesn't work. I don't know why.
Rethinkdb query r.db('testRealtime').table('messages').changes()
Since i'm using angular2. Here's the Service I created
import * as io from 'socket.io-client'
export class ChatService {
private url = 'http://localhost:5000'
private socket;
getMessages() {
this.socket = io(this.url);
this.socket.on('messages', function(data){
console.log(data.new_val.query_engine)
})
}
}
On my component, I just call the getMessages form service. Nothing to worry about angular code. I think it is more about the connection of socket.io and rethinkdb.
Any help would be appreciated. Thanks.

pg-promise hangs after six queries

I'm working on a project using pg-promise. I've tried querying a few different ways with pg-promise but they all seem to cause it to hang after 6 queries.
It seems to me like the connections aren't being closed but I can't find anything in the documentation about closing a connection after a query.
Here's what I have
var cn = {
host: 'localhost',
port: 5432,
database: 'db',
user: 'user',
password: 'password'
};
var db = pgp(cn);
function query(sql, params) {
return db.task(function (t) {
// this = t = task protocol context;
// this.ctx = task config + state context;
return t.query(sql, params);
})
.then(function (events) {
// success;
console.log(events);
})
.catch(function (error) {
// error;
});
}
I also tried using a shared connection, object but the documentation recommended using tasks. Does anyone know what's going on here?
I'm not sure if this will be helpful to anyone in the future. But my problem was not return requests to the browser.
I hit the maximum number of connections and no responses to the browser made it appear to be hanging to me. I didn't realize requests is node/express won't automatically return like they do with php/apache.

Node.js mongodb-native driver authentication in cloudfoundry

I'm currently trying to mess around with Node and Mongo for a bit of self learning. Ive been looking at various blog entries and have been messing with getting a simple blog written in node with a mongo db working.
Anyway I'm having trouble making it work in cloudfoundry. I've looked on the mongodb-native usergroup about authentication and found some node script:
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
ArticleProvider = function(dbname,host, port,username,password) {
this.db= new Db(dbname, new Server(host, port, {auto_reconnect: true}, {}));
this.db.open(function(){
this.db.authenticate(username, password, function(err, db) {
callback(err, db);
});
});
};
I can't for the life of me get this working.
this.db.authenticate(username, password, function() {});
^
TypeError: Cannot call method 'authenticate' of undefined
at /home/ben/NodeJS/sandbox/NodeBlog/articleprovider-mongodb.js:10:17
at /home/ben/NodeJS/sandbox/NodeBlog/node_modules/mongodb/lib/mongodb/db.js:81:14
at /home/ben/NodeJS/sandbox/NodeBlog/node_modules/mongodb/lib/mongodb/connections/server.js:76:11
at /home/ben/NodeJS/sandbox/NodeBlog/node_modules/mongodb/lib/mongodb/admin.js:16:12
at [object Object].<anonymous> (/home/ben/NodeJS/sandbox/NodeBlog/node_modules/mongodb/lib/mongodb/admin.js:124:12)
at [object Object].emit (events.js:67:17)
at [object Object].<anonymous> (/home/ben/NodeJS/sandbox/NodeBlog/node_modules/mongodb/lib/mongodb/connections/server.js:97:12)
at [object Object].emit (events.js:64:17)
at Socket.<anonymous> (/home/ben/NodeJS/sandbox/NodeBlog/node_modules/mongodb/lib/mongodb/connection.js:108:16)
at Socket.emit (events.js:64:17)
Anyone able to point out where I'm being a complete facepalmer would be much appreciated.
I have also faced same kind of problem. Trying harder I have found the solutions.
This may be very helpful to all the mongodb developers.
var ArticleProvider = function(host, port, username, password) {
this.db= new Db('my_db', new Server(host, port, {auto_reconnect: true}, {}));
this.db.open(function(err,data){
if(data){
data.authenticate(username, password,function(err2,data2){
if(data2){
console.log("Database opened");
}
else{
console.log(err2);
}
});
}
else{
console.log(err);
}
});
};
Cheers..
The easiest way connect this is to use a mongourl (mongodb://localhost:27017/db...) and the connect function in the node-mongodb-native drivers.
Cloudfoundry starts a very specific authenticated database and then tells you about connecting to that database within the environment variables, which can make it tougher to debug. Ideally you want it to work on both your local machine and on Cloudfoundry in basically the same way.
Fortunately, I posted an article on MongoDB.org that walks you through a simple Cloudfoundry setup. It has step-by-step instructions from zero to up and running both locally and on Cloudfoundry.
Plus there's a github code sample.