-1

I want to onverting mongodb Binary _id to UUID using node so in order a googling and find my response at this post :

I want to insert this UUId into postgres database.This is my pg function on node.js:

function insert(arg) {
    console.log('insert location');
    arg.forEach(element => {
        (async () => {
            await pool.query(
                `insert into public."Location" ("Id", "Lat", "Lng", "CreationDateTime", "DeviceId", "Topic", "UserId") 
            VALUES ('${uuidv1()}', ${element.Lat}, ${element.Lng}, $1, ${element.DeviceId}, $2, $3)`,[element.CreationDateTime, element.Topic,Bin2HexUUID(element.UserId)]);
        })();
    });
}

This is element.UserId :

Binary {_bsontype: "Binary", sub_type: 4, position: 16, …}
_bsontype:"Binary"

and this is Bin2HexUUID method:

function Bin2HexUUID(bin){
    var hex = new Buffer.alloc(bin, 'base64').toString('hex');
    return hex.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, function (){
        return arguments[1]+"-"+arguments[2]+"-"+arguments[3]+"-"+arguments[4]+"-"+arguments[5];
    });
}

When i run script i got this error:

new Buffer.alloc(bin, 'base64').toString('hex')
NodeError: The "size" argument must be of type number. Received type object
----------------------
(node:2292) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "size" argument must be of type number. Received type object

For first time i used new Buffer(bin, 'base64').toString('hex') but seems new Buffer is deprecated..

This is my Node and Npm version:

node -v
v10.8.0

npm -v
6.2.0
Cyrus the Great
  • 2,571
  • 1
  • 20
  • 65

2 Answers2

2

The size argument inBuffer.alloc(size), not unreasonably, requires a number, because it's an argument that tells the method how many bytes to allocate.

Your Bin2HexUUID(element.UserId) is passing the element.UserId object itself to this method (your error message is telling you that when it says "Received type object"). That's not what the method wants. What it wants is the size (length) of Element.UserId.

So, get the length of Element.UserId and pass that instead.

BobRodes
  • 5,580
  • 2
  • 21
  • 25
1

I changed this part

Bin2HexUUID(element.UserId)

to this:

Bin2HexUUID(element.UserId.buffer)]);

and method :

function Bin2HexUUID(bin){
    var hex = new Buffer.from(bin, 'base64').toString('hex');
    return hex.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, function (){
        return arguments[1]+"-"+arguments[2]+"-"+arguments[3]+"-"+arguments[4]+"-"+arguments[5];
    });
}

I hope this changes help to guys.

Cyrus the Great
  • 2,571
  • 1
  • 20
  • 65