mongoose-uuid icon indicating copy to clipboard operation
mongoose-uuid copied to clipboard

How to get an _id to UUID string after populate ?

Open ystreibel opened this issue 5 years ago • 1 comments

Hi,

I don't understand why is not possible to have an UUID String representation after a populate ?

This is the test code that I tried:

it('should work', function(cb) {
      Photo.findOne({_id: '7c401d91-3852-4818-985d-7e7b79f771c2'}).populate('pet').exec(function(err, photo) {
        (photo.pet).should.exist;
        (photo.pet.name).should.equal('Sammy');

        var photoJSON = photo.toJSON();

        cb(err);
      });
    });

And the error:

TypeError: photo.toJSON is not a function
    at /Users/username/Projects/mongoose-uuid/test/index.js:168:33
    at /Users/username/Projects/mongoose-uuid/node_modules/mongoose/lib/model.js:4759:16
    at /Users/username/Projects/mongoose-uuid/node_modules/mongoose/lib/utils.js:263:16
    at _hooks.execPost (node_modules/mongoose/lib/query.js:4074:11)
    at /Users/username/Projects/mongoose-uuid/node_modules/kareem/index.js:135:16
    at processTicksAndRejections (internal/process/next_tick.js:74:9)

ystreibel avatar Mar 26 '19 16:03 ystreibel

I created an helpers like this:

'use strict';

module.exports = {
    ToUUID: ToUUID
};

function ToUUID(hex) {
    var a =  hex.substr(0, 2) + hex.substr(2, 2)  + hex.substr(4, 2) + hex.substr(6, 2);
    var b =  hex.substr(8, 2) + hex.substr(10, 2);
    var c =  hex.substr(12, 2) + hex.substr(14, 2);
    var d = hex.substr(16, 16);
    hex = a + b + c + d;
    var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12);
    return '"' + uuid + '"';
}

and call it after populate:

User.findOne({ _id: id})
        .select("-password")
        .populate(options)
        .lean()
        .exec((err, user) => {
            if (err) {
                res.send(err);
            } else {
                user._id = uuid.ToUUID(user._id.toString('hex'));
                res.json(user);
            }
        });

But I need something more generic to apply in all UUID's property in my populated user.

ystreibel avatar Mar 26 '19 16:03 ystreibel