Skip to content

Commit

Permalink
fix: add mongoose.isValidObjectId() function to test whether Mongoo…
Browse files Browse the repository at this point in the history
…se can cast a value to an objectid

Fix #3823
  • Loading branch information
vkarpov15 committed Nov 17, 2019
1 parent a3b4ea1 commit 3e9faef
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
45 changes: 45 additions & 0 deletions lib/index.js
Expand Up @@ -933,6 +933,51 @@ Mongoose.prototype.DocumentProvider = require('./document_provider');

Mongoose.prototype.ObjectId = SchemaTypes.ObjectId;

/**
* Returns true if Mongoose can cast the given value to an ObjectId, or
* false otherwise.
*
* ####Example:
*
* mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true
* mongoose.isValidObjectId('0123456789ab'); // true
* mongoose.isValidObjectId(6); // false
*
* @method isValidObjectId
* @api public
*/

Mongoose.prototype.isValidObjectId = function(v) {
if (v == null) {
return true;
}
const base = this || mongoose;
const ObjectId = base.driver.get().ObjectId;
if (v instanceof ObjectId) {
return true;
}

if (v._id != null) {
if (v._id instanceof ObjectId) {
return true;
}
if (v._id.toString instanceof Function) {
v = v._id.toString();
return typeof v === 'string' && (v.length === 12 || v.length === 24);
}
}

if (v.toString instanceof Function) {
v = v.toString();
}

if (typeof v === 'string' && (v.length === 12 || v.length === 24)) {
return true;
}

return false;
};

/**
* The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for
* declaring paths in your schema that should be
Expand Down
6 changes: 6 additions & 0 deletions test/index.test.js
Expand Up @@ -712,6 +712,12 @@ describe('mongoose module:', function() {
});
});

it('isValidObjectId (gh-3823)', function() {
assert.ok(mongoose.isValidObjectId('0123456789ab'));
assert.ok(mongoose.isValidObjectId(new mongoose.Types.ObjectId()));
assert.ok(!mongoose.isValidObjectId(6));
});

describe('exports', function() {
function test(mongoose) {
assert.equal(typeof mongoose.version, 'string');
Expand Down

0 comments on commit 3e9faef

Please sign in to comment.