Fred J.
Fred J.

Reputation: 6039

Filter Mongo document by date in Meteor

This Meteor server code parses html and gets string like "09/03/2017" and saves it to a mongodb collection like this:

const date = ResObj.$(this).next().html().trim();
const dArr = date.split('/');
const dObj = new Date(parseInt(dArr[2]), parseInt(dArr[1]) - 1, parseInt(dArr[0]));
myCol.update({_id:'abc', {$set:{date: dObj}}});

Later I need to return the documents between and include 2 dates say 09/03/2017. The search string is being received from the client in the formate 2017-03-09.

myCol.find({date: {$gte: start, $lte: end}})

Moment.js is also installed. How can I do this so that the output is in the formate DD/MM/YYYY? thx

Upvotes: 1

Views: 470

Answers (1)

Sean
Sean

Reputation: 2729

What you want to do is store your date as a date object, that way you can query against it in the DB.

To do that using moment, you need to parse the string in to a moment object. This is telling moment to create a date object using the date provided and telling it what format the date is in so it knows which is the days/months etc.

const dateObj = moment(date, "DD/MM/YYYY").toDate()

You are then using the moment toDate() function to convert that in to a date object which you can store in the DB.

Save that to the DB

myCol.update({_id:'abc', { $set:{ date: dateObj }}});

Then, when you are back on the client you can format the output date using moment again

const formattedDate = moment(dateFromDB).format("DD/MM/YYYY");

Basically, you always want to store your dates in the DB as date objects, that way they can be used in querys and sorted etc. You only want to convert them back to strings using format() back on the client.

Upvotes: 0

Related Questions