0

I am using stitch function to get the last 7 days from event collection.below is my code.this is execute in stitch function.

exports = async function() {
var events = context.services.get("mongodb-atlas").db("utilo").collection("events");
var today = new Date();
var lastWeek = BSON.Timestamp(today.setDate(today.getDate()-7),0);
console.log(lastWeek);
var document = null;
do{
    document = await cursor.next();
    if(document){
        var result = {};
        result.community = document._id;
        result.data.newUsersCount = await events.count({community:document._id,type:"join",status:"completed",ts:{$gt:lastWeek}}); 
}}
}

In the above code, I tried to get last 7 days records from event collection.Here (today.setDate(today.getDate()-7),0) getting the correct Timestamp value but after adding BSON.Timestamp, the timestamp will change to lower year or higher year like either 2004 or 2024. without changing the Timestamp value, can we convert to the Timestamp?

How can i store value in last week like TImestamp(1520801145,0)?

or How to write the code for get the last 7 days record from events collection (ts stored in timestamp) enter image description here

Ramesh Reddy
  • 127
  • 2
  • 13
  • Use [moment.js](https://momentjs.com/docs/#/manipulating/) to manipulate Date values, there it is much easier and more reliable. – Wernfried Domscheit Feb 28 '20 at 07:32
  • BSON.Timestamp expects the date to be number of seconds since epoch, I believe Date store number of milliseconds since epoch. I'm not sure it's even defined how to deal with values larger than 32 bits. – Joe Feb 28 '20 at 08:54
  • See [documentation](https://docs.mongodb.com/manual/reference/bson-types): *The BSON timestamp type is for internal MongoDB use. For most cases, in application development, you will want to use the BSON **date** type.* - I am not sure if you use the right data type. Anyway try `BSON.Timestamp(moment().subtract(7, 'days').toDate());` or `BSON.Timestamp(moment().subtract(7, 'days').unix());` (perhaps multiplied by 1000). Actually my first attempt would be `var lastWeek = moment().subtract(7, 'days').toDate();` – Wernfried Domscheit Feb 28 '20 at 09:06
  • @WernfriedDomscheit please check the attached screenshot. in events collection ts stored as timestamp. so how to get last 7days from current date? how to use moment.js for timestamp? – Ramesh Reddy Feb 29 '20 at 02:57
  • Please don't paste images, use formatted text. – Wernfried Domscheit Feb 29 '20 at 06:51
  • I gave the commands in my comments. What is not clear with it? – Wernfried Domscheit Feb 29 '20 at 06:53

0 Answers0