如何使用URI和服务器连接到MongoDB服务器

时间:2017-07-09 18:54:10

标签: node.js mongodb asynchronous synchronous

我想对我的mongoDB进行同步查询,npm指示我使用mongo-sync,如下所示:

var Server = require("mongo-sync").Server;
var server = new Server('127.0.0.1');
var result = server.db("test").getCollection("posts").find().toArray();
console.log(result);
server.close();

但是,我的数据库位于远程位置,所以我有connection string(uri)。通常,我会使用MongoClient这样的uri,如下所示:

var MongoClient = require('mongodb').MongoClient;
uri = mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

MongoClient.connect(uri, function(err, db) {
    // I'd read/update my DB right here
    // But this is asynchronous...
});

但是mongo-sync没有MongoClient;它只有一台服务器。那么在这种情况下如何建立连接呢?

调试更新 我现在收到这个错误:

Error: Error: connect ENOENT //heroku_7cr19362
    at Object.exports._errnoException (util.js:1026:11)
at exports._exceptionWithHostPort (util.js:1049:20)
at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1136:14)
Followed by:
    at DB.open (/Users/Chege/NodeJS_Projects/node_modules/mongo-sync/lib/mongo-sync.js:27:13)
at Server.db (/Users/Chege/NodeJS_Projects/node_modules/mongo-sync/lib/mongo-sync.js:50:10)
at /Users/Chege/NodeJS_Projects/Constructing_the_Database/UpdateDB.js:28:22

导致错误的代码是:

var mongoURI = "mongodb://heroku_7cr19362:{PASSWORD}@ds153352.mlab.com:53352/heroku_7cr19362"

Fiber(function() {
    var server = new Server("mongodb://heroku_7cr19362:{PASSWORD}@ds153352.mlab.com:53352/");
    var result = server.db('heroku_7cr19362').getCollection("songs").find().toArray();
    console.log(result);
    console.log("Last statement");
}).run();

所以我目前的问题是:URI的哪一部分用于实例化服务器实例?现在,我正在尝试URI的不同子串,但解释什么在哪里以及为什么会很棒!

1 个答案:

答案 0 :(得分:1)

只需将连接URI替换为“127.0.0.1”。

var Server = require("mongo-sync").Server;
var server = new Server('mongodb://someaksdmkaasdk');
var result = server.db("test").getCollection("posts").find().toArray();
console.log(result);
server.close();
相关问题