node.js - 使用 Node 在 Heroku 上设置 mongodb

标签 node.js mongodb heroku

在我的本地主机上,我有以下 Node 代码来设置 mongoDB 数据库名称“dbname”:

users.js:

var MongoClient = require("mongodb").MongoClient,
    Connection = require("mongodb").Connection,
    Server = require("mongodb").Server;

Users = function(host, port) {
  var mongoClient = new MongoClient(new Server(host, port));
  mongoClient.open(function (){});
  this.db = mongoClient.db("dbname");
};

Users.prototype.getCollection = function (callback) {
  this.db.collection("users", function (error, users) {
    if (error) callback(error);
    else callback(null, users);
  });
};

Users.prototype.findAll = function (callback) {
  this.getCollection(function (error, users) {
    if (error) {
      callback(error);
    } else {
      users.find().toArray(function (error, results) {
        if (error) {
          callback(error);
        } else {
          callback(null,results);
        }
      });
    }
  });
}

// Bunch of other prototype functions...

exports.Users = Users;

我喜欢将上述数据库功能放在一个文件中,然后在我的主服务器文件中要求该文件,如下所示:

server.js:

var Users = require("./users").Users;
var users = new Users("localhost", 27017);
users.findAll(function (err, user) {
  // Do something
});

要在本地主机上运行它非常简单。在命令行中,我只需输入以下内容:

$ mongod # to launch the database server
$ node server.js # to launch the web server

而且效果很好。然而,现在我正在尝试使用 mongolab 插件将整个事情推到 Heroku 上

heroku addons:add mongolab

但是数据库没有运行,我不知道如何让它运行。 This tutorial解释了如何使用 mongolab URI 设置 mongodb,但这不是我的代码的工作方式,我使用主机和端口,并基于此创建一个新服务器。我应该如何更改我的代码才能使其在 heroku 应用程序上运行?我想将数据库代码与原型(prototype)函数一起保存在一个单独的文件中。

最佳答案

按照示例here在“MongoClient.connect”部分。

本质上,您需要更改这部分代码:

Users = function(host, port) {
  var mongoClient = new MongoClient(new Server(host, port));
  mongoClient.open(function (){});
  this.db = mongoClient.db("dbname");
};

使用 mongoClient.connect() 而不是新的 MongoClient:

Users = function(url) {
  MongoClient.connect(url, function(err, db) {
    // Find better way to set this since this callback is asynchronous.
    this.db = db;
  });
};

如果您使用的是 Node,我建议使用诸如 mongoose npm install mongoose 之类的库来处理 mongodb 交互。看我的回答here了解如何构建架构。

关于node.js - 使用 Node 在 Heroku 上设置 mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20390967/

相关文章:

javascript - 引用错误: document is not defined at compile/Electron

node.js - tsc 忽略我的 tsconfig.json 文件

heroku - 角色 "username"heroku Nodejs 的连接过多 - 什么是 yobuko?

java - Mongo JSON 到 Java POJO 映射

nginx - 80 端口上的 heroku + nginx

php - Heroku 上的 Laravel 强制执行 HTTP

javascript - NodeJS/Express/Mean Stack

javascript - Nodejs : run promises sequentially

mongodb - 如何统计mongodb中游标的迭代次数?

node.js - 如何通过 NodeJS 的 MongoDB native 驱动程序执行 db.copyDatabase?