Last active
December 12, 2019 12:00
-
-
Save amitkumar/2221ad9ed9d425a76068a9b6944fa3a1 to your computer and use it in GitHub Desktop.
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = input.constructor.name.toLowerCase(); | |
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 = input._id.constructor.name.toLowerCase(); | |
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