Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert the timestamp in milliseconds as NumberLong in MongoDB using NodeJS

I new to nodejs and trying implement mongodb insert of current timestamp as milliseconds using nodejs its getting inserted as double value. Can anyone help me how to insert this as NumberLong value.

var data = {
        myId : uniqueId,
        Timestamp : Date.now(),   ---> This one is getting inserted as double.
        userData : applicationData
      }
    }

I also try to insert like this but its getting insert as String.

 var mongo=require('mongodb');
 var Long = mongo.Long;

 var data = {
        myId : uniqueId,
        Timestamp : Long.fromString((Date.now() + "")), ---> This one is getting inserted as String.
        userData : applicationData
      }
    }
like image 325
Kamalanathan Avatar asked Jan 21 '17 09:01

Kamalanathan


1 Answers

This is because JavaScript Numbers are Always 64-bit Floating Point. You can use Mongo driver's Long ( https://mongodb.github.io/node-mongodb-native/api-bson-generated/long.html ) to get rid of this problem.

var Long = require('mongodb').Long;
var current_millies = new Date().getTime();

var data = {
 myId : uniqueId,
 timestamp : Long.fromNumber(current_millies),
 userData : applicationData
}
like image 114
karthikdivi Avatar answered Oct 20 '22 14:10

karthikdivi