uuid-mongodb
uuid-mongodb copied to clipboard
Switch to Buffer when using Binary in Mongoose
Referencing from my Issue #8
@alokrajiv does this work for you? I'm having issues with it in my environment
@cdimascio yes, we have been using a helper function like this now for quite some time. No issues:
export function attachPKUUID(schema: mongoose.Schema) {
// add buffer to store a BSON UUID
schema.add({
_id: {
type: Buffer,
default: () => MUUID.v4(),
},
});
// no need for auto getter for _id will add a virtual later
schema.set("id", false);
// virtual getter for custom _id
schema.virtual("id")
.get(function () {
return MUUID.from(this._id.toBSON()).toString();
})
.set(function (val: string) {
this._id = MUUID.from(val);
});
}
whats the issue in your environment ?
When i use the above, i get the following error
/Users/cdimascio/git/uuid-mongodb/example/node_modules/mongoose/lib/schema/buffer.js:184
throw new CastError('buffer', value, this.path);
^
CastError: Cast to buffer failed for value "Binary {
_bsontype: 'Binary',
sub_type: 4,
position: 16,
buffer: <Buffer 93 08 c9 15 22 77 4b af 8c d8 6d 75 05 53 df c5>,
toString: [Function: bound ] }" at path "_id"
at new CastError (/Users/cdimascio/git/uuid-mongodb/example/node_modules/mongoose/lib/error/cast.js:29:11)
at SchemaBuffer.cast (/Users/cdimascio/git/uuid-mongodb/example/node_modules/mongoose/lib/schema/buffer.js:184:9)
at SchemaBuffer.SchemaType.applySetters (/Users/cdimascio/git/uuid-mongodb/example/node_modules/mongoose/lib/schematype.js:969:12)
at SchemaBuffer.SchemaType.getDefault (/Users/cdimascio/git/uuid-mongodb/example/node_modules/mongoose/lib/schematype.js:916:25)
at $__applyDefaults (/Users/cdimascio/git/uuid-mongodb/example/node_modules/mongoose/lib/document.js:375:22)
at model.Document (/Users/cdimascio/git/uuid-mongodb/example/node_modules/mongoose/lib/document.js:150:5)
at model.Model (/Users/cdimascio/git/uuid-mongodb/example/node_modules/mongoose/lib/model.js:97:12)
at new model (/Users/cdimascio/git/uuid-mongodb/example/node_modules/mongoose/lib/model.js:4425:15)
at Object.<anonymous> (/Users/cdimascio/git/uuid-mongodb/example/ex2-mongoose.js:41:15)
In order to solve it in my environment, I did the following:
// 1. Define a simple schema
const kittySchema = new mongoose.Schema({
_id: {
type: 'object',
value: { type: 'Buffer' },
default: () => MUUID.v4(),
},
title: String,
});
Note, i'm using mongoose v5.7.5 and v3.3.4". What are you using? For reference, my full example is here