I spent several hours tracking this one down. The problem came down to my use of Mongoose. I was using Mongoose schemas for some of my Collections and not using Mongoose for others. Here's the file containing my problematic code:
// Some common MongoDb operations and data.
'use strict';
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var logger = require('./Logger');
var mongoose = require('mongoose');
// TODO: Take this out for production.
mongoose.set('debug, true');
var PSSharingInvitations = require('./PSSharingInvitations')
var connectedDb = null;
// Call this just once, at the start of the server.
// TODO: Need better error handling when can't initially connect. Right now have an ugly looking error when Mongo is not already started and we try to start our server.
exports.connect = function(mongoDbURL) {
MongoClient.connect(mongoDbURL, function(err, db) {
assert.equal(null, err);
if (!db) {
logger.error("**** ERROR ****: Cannot connect to MongoDb database!");
}
else {
mongoose.connect(mongoDbURL);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// SCHEMA's
exports.SharingInvitation = PSSharingInvitations.buildSchema(mongoose);
logger.info("Mongoose: Connected to MongoDb database");
});
connectedDb = db;
logger.info("Mongo: Connected to MongoDb database");
}
});
};
exports.db = function () {
return connectedDb;
};
// Call this just once, when the server shuts down.
exports.disconnect = function() {
};
The problem turned out to be the line:
connectedDb = db;
Where db was the mongoose.connection. That is, I was using the mongoose.connection as my db for MongoDB Collections that were not using Mongoose. This caused intermittent errors.
The revised (and so far working!) code is as follows:
exports.connect = function(mongoDbURL) {
MongoClient.connect(mongoDbURL, function(err, db) {
assert.equal(null, err);
if (!db) {
logger.error("**** ERROR ****: Cannot connect to MongoDb database!");
}
else {
connectedDb = db;
logger.info("Mongo: Connected to MongoDb database");
mongoose.connect(mongoDbURL);
var connectedMongooseDb = mongoose.connection;
connectedMongooseDb.on('error', console.error.bind(console, 'connection error:'));
connectedMongooseDb.once('open', function() {
// SCHEMA's
exports.SharingInvitation = PSSharingInvitations.buildSchema(mongoose);
logger.info("Mongoose: Connected to MongoDb database");
});
}
});
};
ObjectID.createFromHexStringmethod anywhere in the docs. Have you tried simplyObjectId(<hexadecimal>), e.g.var id = ObjectId("507f1f77bcf86cd799439011")?createFromHexStringin mongodb.github.io/node-mongodb-native/api-bson-generated/…. I posted what turned out to be the problem, below. Thanks.