繁体   English   中英

如何将mongoose重新连接到另一台远程服务器?

[英]How to reconnect mongoose to another remote server?

我是node.js和mongoose的新手,如何将mongoose重新连接到另一台远程服务器? 在我的文件的开头

var mongoose = require('mongoose')

并连接到localhost,

后来我的代码

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

并且我总是Successfully connected to: remote但是当我通过id看下来打印查找文档时,我总是从本地数据库获取(我导入的模式如require Person = mongoose.model('Person'); )。 如果我已经连接到本地,如何重新连接到远程。

mongoose有两种初始化连接的方法:

  1. 使用默认连接“对象”
  2. 从灰尘中创建连接

在这里,您将创建一个连接,但使用另一个模型。 模型与数据库(普通数据库,副本集或集群)相关联,因此您无法访问正确的主机。

您必须使用默认连接(使用mongoose.connect而不是mongoose.createConnection )或在您正在使用的新连接中创建模型。 在你的例子中:

  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连接到mongoose.connection 这不是您创建的新连接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM