Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fixed up _writeConcern error handling

  • Loading branch information...
commit 6fbec6b65b14a7f88699d70071276bb29d6f5e99 1 parent 0480463
@christkv christkv authored
View
64 examples/admin.js
@@ -1,49 +1,45 @@
-var Db = require('../lib/mongodb').Db,
- Connection = require('../lib/mongodb').Connection,
- Server = require('../lib/mongodb').Server;
+var Db = require('../lib/mongodb').Db
+ , Connection = require('../lib/mongodb').Connection
+ , Server = require('../lib/mongodb').Server
+ , format = require('util').format;
var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT;
+
console.log("Connecting to " + host + ":" + port);
-var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});
-db.open(function(err, db) {
+Db.connect(format("mongodb://%s:%s/node-mongo-examples?w=1", host, port), function(err, db) {
db.dropDatabase(function(err, result){
db.dropCollection('test', function(err, result) {
- db.createCollection('test', function(err, collection) {
-
- // Erase all records in collection
- collection.remove({}, function(err, r) {
- db.admin(function(err, admin) {
+ var collection = db.collection('test');
+ // Erase all records in collection
+ collection.remove({}, function(err, r) {
+ var admin = db.admin();
- // Profiling level set/get
- admin.profilingLevel(function(err, profilingLevel) {
- console.log("Profiling level: " + profilingLevel);
- });
+ // Profiling level set/get
+ admin.profilingLevel(function(err, profilingLevel) {
+ console.log("Profiling level: " + profilingLevel);
+ });
- // Start profiling everything
- admin.setProfilingLevel('all', function(err, level) {
- console.log("Profiling level: " + level);
+ // Start profiling everything
+ admin.setProfilingLevel('all', function(err, level) {
+ console.log("Profiling level: " + level);
- // Read records, creating a profiling event
- collection.find(function(err, cursor) {
- cursor.toArray(function(err, items) {
- // Stop profiling
- admin.setProfilingLevel('off', function(err, level) {
- // Print all profiling info
- admin.profilingInfo(function(err, info) {
- console.dir(info);
+ // Read records, creating a profiling event
+ collection.find().toArray(function(err, items) {
+ // Stop profiling
+ admin.setProfilingLevel('off', function(err, level) {
+ // Print all profiling info
+ admin.profilingInfo(function(err, info) {
+ console.dir(info);
- // Validate returns a hash if all is well or return an error hash if there is a
- // problem.
- admin.validateCollection(collection.collectionName, function(err, result) {
- console.dir(result);
- db.close();
- });
- });
- });
+ // Validate returns a hash if all is well or return an error hash if there is a
+ // problem.
+ admin.validateCollection(collection.collectionName, function(err, result) {
+ console.dir(result);
+ db.close();
});
- });
+ });
});
});
});
View
157 examples/blog.js
@@ -1,6 +1,7 @@
-var Db = require('../lib/mongodb').Db,
- Connection = require('../lib/mongodb').Connection,
- Server = require('../lib/mongodb').Server;
+var Db = require('../lib/mongodb').Db
+ , Connection = require('../lib/mongodb').Connection
+ , Server = require('../lib/mongodb').Server
+ , format = require('util').format;
var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT;
@@ -8,94 +9,84 @@ var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NO
var LINE_SIZE = 120;
console.log("Connecting to " + host + ":" + port);
-var db = new Db('node-mongo-blog', new Server(host, port, {}), {native_parser:true});
-db.open(function(err, db) {
+Db.connect(format("mongodb://%s:%s/node-mongo-blog?w=1", host, port), function(err, db) {
db.dropDatabase(function(err, result) {
console.log("===================================================================================");
console.log(">> Adding Authors");
- db.collection('authors', function(err, collection) {
- collection.createIndex(["meta", ['_id', 1], ['name', 1], ['age', 1]], function(err, indexName) {
- console.log("===================================================================================");
- var authors = {};
-
- // Insert authors
- collection.insert([{'name':'William Shakespeare', 'email':'william@shakespeare.com', 'age':587},
- {'name':'Jorge Luis Borges', 'email':'jorge@borges.com', 'age':123}], function(err, docs) {
- docs.forEach(function(doc) {
- console.dir(doc);
- authors[doc.name] = doc;
- });
- });
+ var collection = db.collection('authors');
+ collection.createIndex(["meta", ['_id', 1], ['name', 1], ['age', 1]], function(err, indexName) {
+ console.log("===================================================================================");
+ var authors = {};
+
+ // Insert authors
+ collection.insert([{'name':'William Shakespeare', 'email':'william@shakespeare.com', 'age':587},
+ {'name':'Jorge Luis Borges', 'email':'jorge@borges.com', 'age':123}], function(err, docs) {
+ docs.forEach(function(doc) {
+ console.dir(doc);
+ authors[doc.name] = doc;
+ });
+ });
- console.log("===================================================================================");
- console.log(">> Authors ordered by age ascending");
- console.log("===================================================================================");
- collection.find({}, {'sort':[['age', 1]]}, function(err, cursor) {
- cursor.each(function(err, author) {
- if(author != null) {
- console.log("[" + author.name + "]:[" + author.email + "]:[" + author.age + "]");
+ console.log("===================================================================================");
+ console.log(">> Authors ordered by age ascending");
+ console.log("===================================================================================");
+ collection.find({}, {'sort':[['age', 1]]}).each(function(err, author) {
+ if(author != null) {
+ console.log("[" + author.name + "]:[" + author.email + "]:[" + author.age + "]");
+ } else {
+ console.log("===================================================================================");
+ console.log(">> Adding users");
+ console.log("===================================================================================");
+ var userCollection = db.collection('users');
+ var users = {};
+
+ userCollection.insert([{'login':'jdoe', 'name':'John Doe', 'email':'john@doe.com'},
+ {'login':'lsmith', 'name':'Lucy Smith', 'email':'lucy@smith.com'}], function(err, docs) {
+ docs.forEach(function(doc) {
+ console.dir(doc);
+ users[doc.login] = doc;
+ });
+ });
+
+ console.log("===================================================================================");
+ console.log(">> Users ordered by login ascending");
+ console.log("===================================================================================");
+ userCollection.find({}, {'sort':[['login', 1]]}).each(function(err, user) {
+ if(user != null) {
+ console.log("[" + user.login + "]:[" + user.name + "]:[" + user.email + "]");
} else {
console.log("===================================================================================");
- console.log(">> Adding users");
- console.log("===================================================================================");
- db.collection('users', function(err, userCollection) {
- var users = {};
-
- userCollection.insert([{'login':'jdoe', 'name':'John Doe', 'email':'john@doe.com'},
- {'login':'lsmith', 'name':'Lucy Smith', 'email':'lucy@smith.com'}], function(err, docs) {
- docs.forEach(function(doc) {
- console.dir(doc);
- users[doc.login] = doc;
- });
- });
-
- console.log("===================================================================================");
- console.log(">> Users ordered by login ascending");
- console.log("===================================================================================");
- userCollection.find({}, {'sort':[['login', 1]]}, function(err, cursor) {
- cursor.each(function(err, user) {
- if(user != null) {
- console.log("[" + user.login + "]:[" + user.name + "]:[" + user.email + "]");
- } else {
- console.log("===================================================================================");
- console.log(">> Adding articles");
- console.log("===================================================================================");
- db.collection('articles', function(err, articlesCollection) {
- articlesCollection.insert([
- { 'title':'Caminando por Buenos Aires',
- 'body':'Las callecitas de Buenos Aires tienen ese no se que...',
- 'author_id':authors['Jorge Luis Borges']._id},
- { 'title':'I must have seen thy face before',
- 'body':'Thine eyes call me in a new way',
- 'author_id':authors['William Shakespeare']._id,
- 'comments':[{'user_id':users['jdoe']._id, 'body':"great article!"}]
- }
- ], function(err, docs) {
- docs.forEach(function(doc) {
- console.dir(doc);
- });
- })
-
- console.log("===================================================================================");
- console.log(">> Articles ordered by title ascending");
- console.log("===================================================================================");
- articlesCollection.find({}, {'sort':[['title', 1]]}, function(err, cursor) {
- cursor.each(function(err, article) {
- if(article != null) {
- console.log("[" + article.title + "]:[" + article.body + "]:[" + article.author_id.toHexString() + "]");
- console.log(">> Closing connection");
- db.close();
- }
- });
- });
- });
- }
- });
- });
- });
+ console.log(">> Adding articles");
+ console.log("===================================================================================");
+ var articlesCollection = db.collection('articles');
+ articlesCollection.insert([
+ { 'title':'Caminando por Buenos Aires',
+ 'body':'Las callecitas de Buenos Aires tienen ese no se que...',
+ 'author_id':authors['Jorge Luis Borges']._id},
+ { 'title':'I must have seen thy face before',
+ 'body':'Thine eyes call me in a new way',
+ 'author_id':authors['William Shakespeare']._id,
+ 'comments':[{'user_id':users['jdoe']._id, 'body':"great article!"}]
+ }
+ ], function(err, docs) {
+ docs.forEach(function(doc) {
+ console.dir(doc);
+ });
+ })
+
+ console.log("===================================================================================");
+ console.log(">> Articles ordered by title ascending");
+ console.log("===================================================================================");
+ articlesCollection.find({}, {'sort':[['title', 1]]}).each(function(err, article) {
+ if(article != null) {
+ console.log("[" + article.title + "]:[" + article.body + "]:[" + article.author_id.toHexString() + "]");
+ console.log(">> Closing connection");
+ db.close();
+ }
+ });
}
});
- });
+ }
});
});
});
View
20 examples/capped.js
@@ -1,26 +1,24 @@
-var Db = require('../lib/mongodb').Db,
- Connection = require('../lib/mongodb').Connection,
- Server = require('../lib/mongodb').Server;
+var Db = require('../lib/mongodb').Db
+ , Connection = require('../lib/mongodb').Connection
+ , Server = require('../lib/mongodb').Server
+ , format = require('util').format;
var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT;
console.log("Connecting to " + host + ":" + port);
-var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});
-db.open(function(err, db) {
+Db.connect(format("mongodb://%s:%s/node-mongo-examples?w=1", host, port), function(err, db) {
db.dropCollection('test', function(err, result) {
// A capped collection has a max size and optionally a max number of records.
// Old records get pushed out by new ones once the size or max num records is
// reached.
db.createCollection('test', {'capped':true, 'size':1024, 'max':12}, function(err, collection) {
- for(var i = 0; i < 100; i++) { collection.insert({'a':i}); }
+ for(var i = 0; i < 100; i++) { collection.insert({'a':i}, {safe:{w:0}}); }
// We will only see the last 12 records
- collection.find(function(err, cursor) {
- cursor.toArray(function(err, items) {
- console.log("The number of records: " + items.length);
- db.close();
- })
+ collection.find().toArray(function(err, items) {
+ console.log("The number of records: " + items.length);
+ db.close();
})
});
});
View
35 lib/mongodb/collection.js
@@ -153,10 +153,7 @@ Collection.prototype.remove = function remove(selector, options, callback) {
, flags);
var self = this;
- var errorOptions = _getWriteConcern(self, options);
-
- // If we have a write concern set and no callback throw error
- if(errorOptions && errorOptions['safe'] != false && typeof callback !== 'function') throw new Error("safe cannot be used without a callback");
+ var errorOptions = _getWriteConcern(self, options, callback);
// Execute the command, do not add a callback as it's async
if(errorOptions && errorOptions != false) {
// Insert options
@@ -281,11 +278,7 @@ var insertAll = function insertAll (self, docs, options, callback) {
}
// Collect errorOptions
- var errorOptions = _getWriteConcern(self, options);
-
- // If we have a write concern set and no callback throw error
- if(errorOptions && errorOptions['safe'] != false && typeof callback !== 'function') throw new Error("safe cannot be used without a callback");
-
+ var errorOptions = _getWriteConcern(self, options, callback);
// Default command options
var commandOptions = {};
// If safe is defined check for error message
@@ -352,9 +345,9 @@ Collection.prototype.save = function save(doc, options, callback) {
var id = doc['_id'];
if(id) {
- this.update({ _id: id }, doc, { upsert: true, safe: _getWriteConcern(this, options) }, callback);
+ this.update({ _id: id }, doc, { upsert: true, safe: _getWriteConcern(this, options, callback) }, callback);
} else {
- this.insert(doc, { safe: _getWriteConcern(this, options) }, callback && function (err, docs) {
+ this.insert(doc, { safe: _getWriteConcern(this, options, callback) }, callback && function (err, docs) {
if (err) return callback(err, null);
if (Array.isArray(docs)) {
@@ -411,11 +404,7 @@ Collection.prototype.update = function update(selector, document, options, callb
var self = this;
// Unpack the error options if any
- var errorOptions = _getWriteConcern(this, options);
-
- // If we have a write concern set and no callback throw error
- if(errorOptions && errorOptions['safe'] != false && typeof callback !== 'function') throw new Error("safe cannot be used without a callback");
-
+ var errorOptions = _getWriteConcern(this, options, callback);
// If we are executing in safe mode or safe both the update and the safe command must happen on the same line
if(errorOptions && errorOptions != false && errorOptions.w != -1 && errorOptions.w != 0) {
// Insert options
@@ -618,7 +607,7 @@ Collection.prototype.findAndModify = function findAndModify (query, sort, doc, o
}
// Unpack the error options if any
- var errorOptions = _getWriteConcern(this, options);
+ var errorOptions = _getWriteConcern(this, options, callback);
// If we have j, w or something else do the getLast Error path
if(errorOptions != null && typeof errorOptions == 'object') {
@@ -979,7 +968,7 @@ Collection.prototype.createIndex = function createIndex (fieldOrSpec, options, c
options = options == null ? {} : options;
// Collect errorOptions
- var errorOptions = _getWriteConcern(this, options);
+ var errorOptions = _getWriteConcern(this, options, callback);
// If we have a write concern set and no callback throw error
if(errorOptions != null && errorOptions != false && (typeof callback !== 'function' && typeof options !== 'function')) throw new Error("safe cannot be used without a callback");
@@ -1021,7 +1010,7 @@ Collection.prototype.ensureIndex = function ensureIndex (fieldOrSpec, options, c
}
// Collect errorOptions
- var errorOptions = _getWriteConcern(this, options);
+ var errorOptions = _getWriteConcern(this, options, callback);
// If we have a write concern set and no callback throw error
if(errorOptions != null && errorOptions != false && (typeof callback !== 'function' && typeof options !== 'function')) throw new Error("safe cannot be used without a callback");
@@ -1607,11 +1596,17 @@ Object.defineProperty(Collection.prototype, "hint", {
/**
* @ignore
*/
-var _getWriteConcern = function(self, options) {
+var _getWriteConcern = function(self, options, callback) {
// Collect errorOptions
var errorOptions = options.safe != null ? options.safe : null;
errorOptions = errorOptions == null && self.opts.safe != null ? self.opts.safe : errorOptions;
errorOptions = errorOptions == null && self.db.safe != null ? self.db.safe : errorOptions;
+
+ // Verify correct behavior of the error conditions
+ if(errorOptions
+ && (errorOptions == true || errorOptions.w >= 1)
+ && typeof callback !== 'function') throw new Error("safe cannot be used without a callback");
+ // Return the error options
return errorOptions;
}
View
34 lib/mongodb/db.js
@@ -1093,13 +1093,8 @@ Db.prototype.createIndex = function(collectionName, fieldOrSpec, options, callba
options = typeof callback === 'function' ? options : callback;
options = options == null ? {} : options;
- // Collect errorOptions
- var errorOptions = options.safe != null ? options.safe : null;
- errorOptions = errorOptions == null && self.safe != null ? self.safe : errorOptions;
-
- // If we have a write concern set and no callback throw error
- if(errorOptions != null && errorOptions != false && (typeof callback !== 'function' && typeof options !== 'function')) throw new Error("safe cannot be used without a callback");
-
+ // Get the error options
+ var errorOptions = _getWriteConcern(this, options, callback);
// Create command
var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options);
// Default command options
@@ -1181,13 +1176,8 @@ Db.prototype.ensureIndex = function(collectionName, fieldOrSpec, options, callba
options = {};
}
- // Collect errorOptions
- var errorOptions = options.safe != null ? options.safe : null;
- errorOptions = errorOptions == null && self.safe != null ? self.safe : errorOptions;
-
- // If we have a write concern set and no callback throw error
- if(errorOptions != null && errorOptions != false && (typeof callback !== 'function' && typeof options !== 'function')) throw new Error("safe cannot be used without a callback");
-
+ // Get the error options
+ var errorOptions = _getWriteConcern(this, options, callback);
// Create command
var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options);
var index_name = command.documents[0].name;
@@ -2109,6 +2099,22 @@ Object.defineProperty(Db.prototype, "state", { enumerable: true
});
/**
+ * @ignore
+ */
+var _getWriteConcern = function(self, options, callback) {
+ // Collect errorOptions
+ var errorOptions = options.safe != null ? options.safe : null;
+ errorOptions = errorOptions == null && self.safe != null ? self.safe : errorOptions;
+
+ // Verify correct behavior of the error conditions
+ if(errorOptions
+ && (errorOptions == true || errorOptions.w >= 1)
+ && typeof callback !== 'function') throw new Error("safe cannot be used without a callback");
+ // Return the error options
+ return errorOptions;
+}
+
+/**
* Legacy support
*
* @ignore
View
2  test/mongo_reply_test.js
@@ -9,7 +9,7 @@ var testCase = require('nodeunit').testCase,
Db = mongodb.Db,
Cursor = mongodb.Cursor,
Collection = mongodb.Collection,
- MongoReply = mongodb.MongoReply,
+ MongoReply = require('../lib/mongodb/responses/mongo_reply').MongoReply,
Server = mongodb.Server,
Long = mongodb.Long,
ObjectID = mongodb.ObjectID,
Please sign in to comment.
Something went wrong with that request. Please try again.