How to get node.js to connect to mongolab using mongoose

11,297

Try using

db = mongoose.connect(uri);

instead of

db = mongoose.createConnection(uri);
Share:
11,297
Bren
Author by

Bren

Updated on July 25, 2022

Comments

  • Bren
    Bren almost 2 years

    I've been trying to use mongoose (module for node.js and mongodb). And tried to get a connection with mongolab up and running. I tried the following at the top of my app.js file, but I couldn't seem to enter the db.on function.

    global.mongoose = require('mongoose');
    var uri = 'mongodb://username:password#####@ds.mongolab.com:#####/db';
    global.db = mongoose.createConnection(uri);
    global.Schema = mongoose.Schema;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function (callback) {
      console.log("db up")
      var userSchema = new Schema({
          name  :  { type: String, default: '' }
        , password   :  { type: String, default: '' }
      });
      var userModel = mongoose.model('User', userSchema);
      var test = new userModel({name: "test", password: "test"})
    
      console.log("me: " + test)
    
      test.save(function (err, test) {
        console.log("saved?")
        if (err) {
          console.log("error");
          return console.error(err);
        }
        console.log("saved!")
      });
    
      console.log("after save");
    
    });
    

    My terminal output was

    /usr/local/bin/node bin/www
    me: { _id: 557f93a8a8b4b8628095bd01, password: 'test', name: 'test' }
    after save
    

    The debugger also seemed to skip the function (my debugging skills on WebStorm are limited though)

    This also didn't work in a more straightforward manner:

    mongoose = require('mongoose');
    var uri = 'mongodb://username:password.mongolab.com:#####/db';
    db = mongoose.createConnection(uri);
    Schema = mongoose.Schema;
    
      var userSchema = new Schema({
          name  :  { type: String, default: '' }
        , password   :  { type: String, default: '' }
      });
      var userModel = mongoose.model('User', userSchema);
      var test = new userModel({name: "test", password: "test"})
    
      console.log("me: " + test)
    
      test.save(function (err, test) {
        console.log("saved?")
        if (err) {
          console.log("error");
          return console.error(err);
        }
        console.log("saved!")
      });
      console.log("after save");
    

    This gave me the same terminal output.

    I'd like to know what steps I need to take to actually start talking to my mongolab database. Also I don't see any collection created on mongolab.