0

I'm running Node v6.11.4 on Ubuntu with Mongoose 4.12.4 and Mongo v3.4.9. I have the following code to add a new record, then read back the following. The save is not getting executed (fluffy.save()).

However, if I replace mongoose.createConnection line with the two lines above it using mongoose.connect, then the whole code works as expected.

// getting-started.js
var mongoose = require('mongoose');

mongoose.Promise = require('bluebird');
var options = {promiseLibrary: require('bluebird')};

//mongoose.connect('mongodb://localhost/test',options);
//var db = mongoose.connection;
var db = mongoose.createConnection('mongodb://localhost/test', options);

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log('We\'re Connected!');

    var kittySchema = mongoose.Schema({
        name: String
    });

// NOTE: methods must be added to the schema before compiling it with mongoose.model()
    kittySchema.methods.speak = function () {
        var greeting = this.name
                ? "Meow name is " + this.name
                : "I don't have a name";
        console.log(greeting);
    }

    var Kitten = mongoose.model('Kitten', kittySchema);

    var silence = new Kitten({name: 'Silence'});
    console.log(silence.name); // 'Silence'

    var fluffy = new Kitten({name: 'fluffy'});
    fluffy.speak(); // "Meow name is fluffy"

    fluffy.save(function (err, fluffy) {
        if (err)
            return console.error(err);
        fluffy.speak();
    }).then((val) => {
        console.log("result: " + val);
        Kitten.find({name: 'fluffy'}, function (err, kittens) {
            if (err)
                return console.error(err);
            console.log("All the kittens found: " + kittens);
        })
    }

    ).catch((err) => console.log("rejected:" + err));



});

Result using mongoose.createConnection:

We're Connected!
Silence
Meow name is fluffy

Result with the updated code using mongo.connect:

We're Connected!
Silence
Meow name is fluffy
result: { __v: 0, name: 'fluffy', _id: 59ed75e7c414e210bc074bf3 }
Meow name is fluffy
All the kittens found: { _id: 59ed635dbcefe203f07a4b35, name: 'fluffy', __v: 0 },{ _id: 59ed63bddfb1de04351704e5, name: 'fluffy', __v: 0 },{ _id: 59ed63ee6c7ca0046872ff4e, name: 'fluffy', __v: 0 },{ _id: 59ed6f5fc816670d3bc0a09e, name: 'fluffy', __v: 0 },{ _id: 59ed6fd49319d20d8944b7e2, name: 'fluffy', __v: 0 },{ _id: 59ed74785885cf0ff23ef0ee, name: 'fluffy', __v: 0 },{ _id: 59ed75e7c414e210bc074bf3, name: 'fluffy', __v: 0 }
user994165
  • 9,146
  • 30
  • 98
  • 165
  • People keep asking this. Don't do that and use `connect()` instead. See [Connections](http://mongoosejs.com/docs/connections.html) in the manual. Is there some article or training source which is prompting you to think you write with `createConnection()`? Seems more than coincidental that there seems to be a rush of questions all doing the same incorrect thing. – Neil Lunn Oct 23 '17 at 05:00
  • It also does not escape attention that all questions seem to be assigning `mongoose.Promise` and then you don't actually use Promises at all in the code. So a possible explanation is seeing the warning message with `.connect()` but then coming to the wrong conclusion, rather than applying the `{ useMongoClient: true }` and promise/callback resolve directly on the method, like the message should be telling you to do. – Neil Lunn Oct 23 '17 at 05:03
  • @Neill Lunn, That Connections link you provided says to use mongoose.createConnection() if you need to create multiple connections. If I don't assign my promise library, I get the following warning: "DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html" whether I use connect() or createConnection(). – user994165 Oct 25 '17 at 01:29
  • @Neill Lunn, I did do what the documentation said. Right below the code you copied is the bluebird example I used. I did set up useMongoClient as you suggested. In any case, none of this had anything to do with the error with createConnection. That was caused by using mongoose.model() instead of db.model(). I pasted working samples in my answer for both connect() and createConnection() and neither has a warning message. – user994165 Oct 25 '17 at 20:30

2 Answers2

2

Based on the answer in Queries hang when using mongoose.createConnection() vs mongoose.connect(), we have to use db.model() not mongoose.model() when using createConnection(). mongoose.model() can only be using be used with connect(). I've pasted two working solutions.

Solution with connect():

var mongoose = require('mongoose');
var util = require('util');

mongoose.Promise = require('bluebird');
var options = {promiseLibrary: require('bluebird'), useMongoClient: true};

var promise = mongoose.connect('mongodb://localhost/test', options);

promise.then(function (db) {
  console.log('We\'re Connected!');

  var kittySchema = mongoose.Schema({
    name: String
  });

  // NOTE: methods must be added to the schema before compiling it with mongoose.model()
  kittySchema.methods.speak = function () {
    var greeting = this.name
      ? "Meow name is " + this.name
      : "I don't have a name";
    console.log(greeting);
  }

  // NOTE: Use mongoose.model() instead of db.model() when using connect().
  var Kitten = mongoose.model('Kitten', kittySchema);

  var fluffy = new Kitten({name: 'fluffy'});
  fluffy.speak(); // "Meow name is fluffy"

  fluffy.save(function (err, fluffy) {
    if (err)
      return console.error(err);
    fluffy.speak();
  })
    .then((val) => {
      console.log("result: " + val);
      Kitten.find({name: 'fluffy'}, function (err, kittens) {
        if (err) {
          return console.error(err);
        }
        console.log("All the kittens found: " + kittens);
      })
    }

    )
    .catch((err) => {
      console.log("Mongo save rejected:" + err);
      process.exit(1);
    }
    );
});

Solution with createConnection():

var mongoose = require('mongoose');
var util = require('util');

mongoose.Promise = require('bluebird');
var options = {promiseLibrary: require('bluebird'), useMongoClient: true};

var promise = mongoose.createConnection('mongodb://localhost/test', options);

promise.then(function (db) {
  var kittySchema = mongoose.Schema({
    name: String
  });

  // NOTE: methods must be added to the schema before compiling it with mongoose.model()
  kittySchema.methods.speak = function () {
    var greeting = this.name
      ? "Meow name is " + this.name
      : "I don't have a name";
    console.log(greeting);
  }

  // NOTE use db.model() instead of mongoose.model when using mongoose.createConnection()
  var Kitten = db.model('Kitten', kittySchema);

  var fluffy = new Kitten({name: 'fluffy'});
  fluffy.speak(); // "Meow name is fluffy"

  fluffy.save(function (err, fluffy) {
    if (err)
      return console.error(err);
    fluffy.speak();
  })
    .then((val) => {
      console.log("result: " + val);
      Kitten.find({name: 'fluffy'}, function (err, kittens) {
        if (err) {
          return console.error(err);
        }
        console.log("All the kittens found: " + kittens);
      })
    })
    .catch((err) => {
      console.log("Mongo save rejected:" + err);
      process.exit(1);
    }
    );
})
  .catch((err) => {
    console.error(`Error connecting to MongoDB: ${err}`);
    process.exit(1);
  }
  );

promise.on("disconnected", function () {
  console.log("Mongoose disconnected");
  process.exit(1);
});

promise.on('err', function () {
  console.error(`Error connecting to MongoDB: ${err}`);
  process.exit(1);
});
user994165
  • 9,146
  • 30
  • 98
  • 165
1

You can work with the connections in this way:

const mongoose = require("mongoose"),
  dbURI = "mongodb://your-host(ex - localhost):your port (ex - 27017)/yourDatabaseName";

mongoose.connect(dbURI);
conn = mongoose.connection;

conn.on("connected", function(){
    console.log("Mongoose connected to " + dbURI);
});

conn.on("error", function(err){
    console.log("Mongoose connection error" + err);
});

conn.on("disconnected", function(){
    console.log("Mongoose disconnected");
});
  • what about being able to handle multiple connections? The documentation suggests using mongoose.createConnection(). – user994165 Oct 25 '17 at 01:15