Skip to main content
3 de 3
conteúdo editado
jsantos1991
  • 2,4mil
  • 4
  • 21
  • 42

Heroku - Connetar com mongoDB addon mLab

Preciso me conetar com a base de dados Mongo usando o addOn mLab. Mas não estou a conseguir inserir nem listar, quando executo em modo local está a funcionar. Tenho a variável configurada:

inserir a descrição da imagem aqui

Alguma ideia do que pode ser?

O meu app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var app = express();


    // Here we find an appropriate database to connect to, defaulting to
    // localhost if we don't find one.
    //'mongodb://heroku_28mj3757:[email protected]:31597/heroku_28mj3757';
    //MONGODB_URI
    var uristring =
    process.env.MONGOLAB_URI ||
    process.env.MONGOHQ_URL||
    'mongodb://localhost/HelloMongoose';

    //


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

    // The http server will listen to an appropriate port, or default to
    // port 5000.

    console.log("O valor da porta é:  " +process.env.PORT);
    console.log("O valor da porta é:  " +uristring);
    var theport = process.env.PORT || 5000;


        // Makes connection asynchronously.  Mongoose will queue up database
    // operations and release them when the connection is complete.
    mongoose.connect(uristring, function (err, res) {
      if (err) {
      console.log ('ERROR connecting to: ' + uristring + '. ' + err);
      } else {
      console.log ('Succeeded connected to: ' + uristring);
      }
    });

module.exports = app;

Rotas onde faço inserção/listar;

   var userSchema = new mongoose.Schema({
      name: String,
      age:  Number
    });


var PUser = mongoose.model('PowerUsers', userSchema);



router.post('/insert', function(req, res, next) {
  //res.send({nome:"nome"}); 
  //console.("Ola mundo");
  //var Inscricaoo = mongoose.model('pessoas', inscricao);

  console.log("Route -  passou aqui ");
   
    // Creating one user.
    var johndoe = new PUser ({
      "name":"sara",
      "age": 25
    });



    // Saving it to the database.
    johndoe.save(function (err, result) {
        console.log("Errroooooo" + err);
    });

    res.send(johndoe);

});


router.get('/userlist', function(req, res, next) {
  //res.send({nome:"nome"}); 
  //console.("Ola mundo");
  //var Inscricaoo = mongoose.model('pessoas', inscricao);

  console.log("Route user list-  passou aqui ");
       // list all .
  PUser.find({}, function(err, users) {
    var userMap = {};

    users.forEach(function(user) {
      userMap[user._id] = user;
    });

    res.send(userMap);  
  });

});

Logs do heroku:

inserir a descrição da imagem aqui

jsantos1991
  • 2,4mil
  • 4
  • 21
  • 42