Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

add ObjectID support for findById

  • Loading branch information...
commit f9174d09868bb44e0d1ab962798a8f1088013bc6 1 parent fa4a1d6
@fengmk2 fengmk2 authored
View
13 lib/mongoskin/collection.js
@@ -178,11 +178,20 @@ SkinCollection.prototype.id = function(hex) {
};
/**
- * use hex id as first argument
+ * use hex id as first argument, support ObjectID and String id
+ *
+ * @param {String/ObjectID} id
+ * @param {Function} callback
+ * @return {Object} cursor
+ * @api public
*/
SkinCollection.prototype.findById = function() {
var args = __slice.call(arguments);
- args[0] = {_id: this.id(args[0])};
+ var _id = args[0];
+ if(!(_id instanceof this.skinDb.db.bson_serializer.ObjectID)) {
+ _id = this.id(_id);
+ }
+ args[0] = {_id: _id};
this.findOne.apply(this, args);
};
View
5 package.json
@@ -21,7 +21,10 @@
"dependencies": {
"mongodb": "*"
},
- "devDependencies": {},
+ "devDependencies": {
+ "expresso": "0.9.2",
+ "should": "0.3.2"
+ },
"directories": {
"lib": "lib/mongoskin"
}
View
45 test/findById.test.js
@@ -0,0 +1,45 @@
+
+/**
+ * Module dependencies.
+ */
+
+var mongoskin = require('../')
+ , should = require('should');
+
+
+module.exports = {
+ 'test findById string id': function() {
+ var db = mongoskin.db('localhost/test');
+ var ObjectID = db.db.bson_serializer.ObjectID;
+ db.bind('article');
+ var now = new Date();
+ var article = {title: 'test article title ' + now.getTime(), created_at: now};
+ db.article.insert(article, function(err, obj) {
+ should.not.exist(err);
+ should.exist(obj);
+ obj.should.have.length(1);
+ article.should.have.property('_id').with.instanceof(ObjectID);
+ obj[0].should.have.property('_id').with.instanceof(ObjectID);
+
+ var count = 2;
+ db.article.findById(article._id.toString(), function(err, obj) {
+ should.not.exist(err);
+ should.exist(obj);
+ obj.should.have.property('_id').with.instanceof(ObjectID);
+ obj._id.should.eql(article._id);
+ if(--count === 0) {
+ db.close();
+ }
+ });
+ db.article.findById(article._id, function(err, obj) {
+ should.not.exist(err);
+ should.exist(obj);
+ obj.should.have.property('_id').with.instanceof(ObjectID);
+ obj._id.should.eql(article._id);
+ if(--count === 0) {
+ db.close();
+ }
+ });
+ });
+ }
+};
Please sign in to comment.
Something went wrong with that request. Please try again.