用猫鼬切换数据库 [英] switching database with mongoose

查看:61
本文介绍了用猫鼬切换数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用猫鼬来切换数据库? 我以为我可以那样做:

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.

例如.

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()
  })
}

这篇关于用猫鼬切换数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆