Skip to content

Instantly share code, notes, and snippets.

@bendytree
Last active September 2, 2016 10:15
Show Gist options
  • Save bendytree/37b68a158ced3741dc8f to your computer and use it in GitHub Desktop.
Save bendytree/37b68a158ced3741dc8f to your computer and use it in GitHub Desktop.
A custom SchemaType for Mongoose that treats `_id` as a string on the mongoose document, but as an ObjectId in the database.
/*
* ObjectIdAsString
*
* A SchemaType for MongooseJS that acts exactly like an ObjectId except that
* the field is handled as a string in the mongoose document.
*
* NOTE: If a document is fetched with `lean:true` then the field is not converted
* to a string. Ugh.
*
* //register the type
* var mongoose = require('mongoose');
* require('./object-id-as-string')(mongoose);
*
* //use it on your schema
* var schema = mongoose.Schema({
* _id: { type: "ObjectIdAsString" },
* ....
* });
* var Thing = mongoose.model("Thing", schema);
*
* //creating a document
* var thing = new Thing();
* thing._id; //this is a string like "43345823304969c878318d12"
*
* //saving
* thing.save(function(err){
* thing._id; //this is still a string
* //the database now has { _id: ObjectId("43345823304969c878318d12") }
* });
*
* //fetching works like normal
* Thing.findOne({ _id: "43345823304969c878318d12" }, function(err, thing){
* thing._id; //this is a string
* });
* Thing.findOne({ _id: { $in: [ObjectId("43345823304969c878318d12")] } }, function(err, thing){
* thing._id; //this is a string
* });
*
* //lean doesn't quite work
* Thing.findOne({ _id: "43345823304969c878318d12" }).lean().exec(function(err, thing){
* thing._id; //this is an ObjectId, not a string
* });
*
*/
var util = require('util');
module.exports = exports = function (mongoose) {
function ObjectIdAsString (path, options) {
//call the standard ObjectId constructor
mongoose.SchemaTypes.ObjectId.call(this, path, options);
//expose the value as a string
this.get(function(val){
return val ? String(val) : val;
});
//defaults to new ObjectId
this.default(function(){
return mongoose.Types.ObjectId();
});
}
//should act like ObjectId
util.inherits(ObjectIdAsString, mongoose.SchemaTypes.ObjectId);
//make sure it hasn't been registered
if (mongoose.SchemaTypes.ObjectIdAsString)
throw new Error('A ObjectIdAsString schema type is already registered.');
//expose it as a SchemaType
mongoose.SchemaTypes.ObjectIdAsString = ObjectIdAsString;
//return schema type
return ObjectIdAsString;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment