switching database with mongoose

Hi is there a way to switch database with mongoose? I thought I could do it like that:

mongoose.disconnect();
mongoose.connect('localhost',db);

but it does not work I receive this error:

Error: Trying to open unclosed connection.

I do not know if it is because is asynchronous

It is asynchronous. If you pass a callback function to disconnect and try to connect to the next database in that callback, it will work.

Ex.

var mongoose = require('mongoose')

mongoose.connect('mongodb://localhost/test1', function() {
  console.log('Connected to test 1')
  mongoose.disconnect(connectToTest2)
})

function connectToTest2() {
  mongoose.connect('mongodb://localhost/test2', function() {
    console.log('Connected to test 2')
    process.exit()
  })
}