Skip to content

Instantly share code, notes, and snippets.

Last active December 12, 2019 12:00
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
A utility method to get the ObjectID from a variety of input types. In working with a Mongoose REST API, I encounter mongoose subdocuments that may or may not be populated, may or may not be hydrated Mongoose models, and _id's that may be coming from the front-end that are just strings. This method allows you to pass in those 3 possibilities and…
const ObjectID = require('mongodb').ObjectID;
* Returns the ObjectId of the object, taking into account
* whether the object is a populated Model, an ObjectId, or
* a string representation of an ObjectID.
* @param {MongooseModel|Object|String} input
* @return ObjectId
module.exports = function(input){
const constructor =;
if (constructor === 'objectid'){ return input; }
if (constructor === 'string'){ return new ObjectID(input); }
// else, assume it's a populated model and has an _id property
const _idConstructor =;
if (_idConstructor === 'objectid') { return input._id; }
// might be a POJO so coerce it to an ObjectID object
return new ObjectID(input._id.toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment