Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create hashid based on mongodb '_id` attribute

I have my mongo db schema as follows:

var MyTable = mongoose.model('items', {
    name: String,
    keyId: String
});

I would like to store keyId as a hashid of '_id' for the item being created. Eg. Say, i add an item to db "Hello world", and mongodb would create some '_id' for the item while inserting.

I would like to make use of the _id so that i could use that and generate a hashid for the same item being inserted. Something like this:

var Hashids = require("hashids"),
    hashids = new Hashids("this is my salt");

var id = hashids.encrypt("507f191e810c19729de860ea");

Is there a way, I could know the id before hand. Or I could let mongodb generate value for my id field based on criteria I specify.

like image 259
jsbisht Avatar asked Mar 26 '26 06:03

jsbisht


1 Answers

You can use pre save middleware to perform operations on the object instance before it gets saved.

var MyTableSchema = new mongoose.Schema({
    name: String,
    keyId: String
});

var Hashids = require("hashids");
MyTableSchema.pre('save', function(next) {
    if (!this.keyId)
        this.keyId = new Hashids("this is my salt").encrypt("507f191e810c19729de860ea");
    next();
});

var MyTable = mongoose.model('items', MyTableSchema);
like image 104
laggingreflex Avatar answered Mar 28 '26 22:03

laggingreflex