简体   繁体   English

使用Node.JS从mongodb转到MongoLab

[英]Going from mongodb to MongoLab using Node.JS

I'm trying to do the same thing this guy's doing here How do I setup MongoDB database on Heroku with MongoLab? 我正在尝试执行此人在此处所做的相同操作如何使用MongoLab在Heroku上设置MongoDB数据库?

The app works on Amazon EC2 and I'm deploying to Heroku with the MongoLabs add-on. 该应用程序可在Amazon EC2上运行,并且我将使用MongoLabs附加组件部署到Heroku。

What exactly should I type to change the mongo connection to the Mongo URI? 我到底应该输入什么来将mongo连接更改为Mongo URI?

Heroku Documentation Heroku文档

/** https://devcenter.heroku.com/articles/getting-started-with-nodejs#write-your-app */

var mongo = require('mongodb');

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/mydb';

mongo.Db.connect(mongoUri, function (err, db) {
  db.collection('mydocs', function(er, collection) {
    collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) {
    });
  });
});

app.js app.js

/** app.js */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path')
  , EmployeeProvider = require('./employeeprovider').EmployeeProvider;

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 8080);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('view options', {layout: false});
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(require('stylus').middleware(__dirname + '/public'));
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

var employeeProvider= new EmployeeProvider('localhost', 27017);

//Routes

app.get('/', function(req, res){
  employeeProvider.findAll(function(error, emps){
       res.render('index', {
            title: 'Employees',
            employees:emps
        });
   });
});

app.get('/employee/new', function(req, res) {
    res.render('employee_new', {
        title: 'New Employee'
    });
});

//save new employee
app.post('/employee/new', function(req, res){
    employeeProvider.save({
    title: req.param('title'),
        name: req.param('name')
    }, function( error, docs) {
        res.redirect('/')
    });
});

app.listen(8080);

employeeprovider.js employeeprovider.js

var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;

EmployeeProvider = function(host, port) {
  this.db= new Db('node-mongo-employee', new Server(host, port, {safe: true},          {auto_reconnect: true}, {}));
  this.db.open(function(){});
};


EmployeeProvider.prototype.getCollection= function(callback) {
  this.db.collection('employees', function(error, employee_collection) {
    if( error ) callback(error);
    else callback(null, employee_collection);
  });
};

//find all employees
EmployeeProvider.prototype.findAll = function(callback) {
    this.getCollection(function(error, employee_collection) {
      if( error ) callback(error)
      else {
        employee_collection.find().toArray(function(error, results) {
          if( error ) callback(error)
          else callback(null, results)
        });
       }
    });
};

//save new employee
EmployeeProvider.prototype.save = function(employees, callback) {
    this.getCollection(function(error, employee_collection) {
      if( error ) callback(error)
      else {
        if( typeof(employees.length)=="undefined")
          employees = [employees];

        for( var i =0;i< employees.length;i++ ) {
          employee = employees[i];
          employee.created_at = new Date();
        }

        employee_collection.insert(employees, function() {
          callback(null, employees);
        });
      }
    });
};

exports.EmployeeProvider = EmployeeProvider;

How would I change the employeeProvider to use the URI instead of the localhost? 我将如何更改employeeProvider以使用URI而不是localhost?

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/mydb';

This line should already be correct without having to change anything. 这行应该是正确的,无需更改任何内容。 The code short-circuits as soon as one of the values exists, so 'mongodb://localhost/mydb' is only used if neither MONGOLAB_URI or MONGOHQ_URL exist in the environment variables. 一旦存在这些值之一,代码就会短路,因此,仅当环境变量中不存在MONGOLAB_URI或MONGOHQ_URL时,才使用“ mongodb:// localhost / mydb”。

That said, chances are a given Heroku app isn't making use of both MongoDB providers, so it makes sense to only include the variable name you intend to use. 就是说,给定的Heroku应用很可能没有同时使用两个MongoDB提供程序,因此仅包含要使用的变量名是有意义的。 My apps, for example, have: 例如,我的应用程序具有:

var mongoUri = process.env.MONGOLAB_URI || 'mongodb://localhost/test'

First check your NODE_ENV environment 首先检查您的NODE_ENV环境

$ heroku config
=== ### Config Vars
MONGODB_URI:           mongodb://heroku_lhwpq2p3:sdvsdvsdvds@sdvsdv.mlab.com:dsvsd/heroku_lsdv
NODE_ENV:              production
NPM_CONFIG_PRODUCTION: true

the name you put in var 您在var中输入的名称

mongoUri = process.env.MONGOLAB_URI || localhost:..

should be : 应该 :

var mongoUri = process.env.MONGODB_URI || localhost:..

if the error still persists then you need to set the NODE_ENV environment variable from development to production like : 如果错误仍然存​​在,则需要从开发到生产设置NODE_ENV环境变量,例如:

$ heroku config:set NODE_ENV="production"
$ heroku config:set NPM_CONFIG_PRODUCTION=true

I was using MongoHQ but its similar, first you need to create user in addon for your database and then add credentials to URI (you should see uri in your mongo addon) example: 我使用的是MongoHQ,但与之类似,首先您需要在addon中为数据库创建用户,然后将凭据添加到URI(在mongo addon中应该看到uri)示例:

mongodb://user:pass@paulo.mongohq.com:10000/app12345678 mongodb://用户:pass@paulo.mongohq.com:10000 / app12345678

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

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