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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With