Save date with DD/MM/YYYY - mongodb

How can I save DD/MM/YYYY format into mongodb database in date type?
After saving it into mongodb, when I retrieved, how can I convert it back to DD/MM/YYYY?
I am using Mongoose.

Better way to store dates in mongodb is store them by using native javascript date object.
They allows you to use some useful methods (comparison, map reduce, ...) in mongodb natively.
Then, you can easily get formatted date by using mongoose virtuals, e.x.:
// describe your schema
var schema = new Schema({
time: Date
}, {
toObject: { getters: true }
});
// schema.formatted_time -> DD/MM/YYYY
schema.virtual('formatted_time').get(function() {
var date = new Date(this.time);
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
});

Related

Is there a date format to use when loading Firestore from json file

I'm loading a json file into Firestore. I have date fields formatted as:
{"createdon":"2019-01-03T20:53:41Z","modifiedon":"2019-02-03T20:53:41Z",
These are stored in Firestore as strings.
The load is done by :
firestore.collection(collectionKey).doc('name1').collection('kitlist').add(data[docKey]).then((res) => {
console.log("Document " + docKey + " successfully written!");
}).catch((error) => {
console.error("Error writing document: ", error);
Is there a way to make the dates load as Firestore timestamps? Should I use a different json date format?
I see you are using the JS SDK, use the native JS Date to upload dates:
{createdon: new Date("2019-01-03T20:53:41Z"), modifiedon:new Date("2019-02-03T20:53:41Z")}

Store and Retrieve Date in dd MMM yyyy format in MongoDB model

I have a MongoDB model that contains a Date field whose type is defined as Date.now. Any date is converted to ISO date format. Inside the model the date is defined as :
xDate : {
type: Date.now,
required: true
}
I pass the current Date as :
var d = new Date();
var temp = d.toISOString();
var subStr = temp.substr(10,temp.length - 1);
var curDate = temp.replace(subStr, "T00:00:00.000Z");
console.log(curDate);
However the date is stored as an ISO String inside the MongoDB schema. I try to query it using Mongoose using the following query:
X.
find({
xDate: curDate
})
.exec(function(err, doc) {
var response = {
status : 200,
message : doc
};
if (err) {
console.log('Error');
response.status = 500;
response.message = err;
} else if (!doc) {
console.log("Documents against the date not found in database" ,curDate);
response.status = 404;
response.message = {
"message" : "Documents not found for " + curDate
};
}
res
.status(response.status)
.json(response.message);
});
I keep getting a blank json array inspite of the data being there. Inside the table the xDate is stored as YYYY-MM-DD format.
The date inside mongo is not stores in ISO string. If you save your model as Date.now, it will save a new Date object, not an ISO string. So one easy way of querying is to query by new Date() object.
Also note that your query is hard to be true, since you will have a hard time getting the exactly same date as your data is stored. I think better option for you is using $lt or $gt filters.
New query should look something like:
let currDate = new Date()
// change the date using class methods
X.find({
xDate: {$lt: currDate}
}).exec...

get records created within 24 hour in sails js

I want to fetch the Posts which are created within 24 hours in sails js. And I am using mongodb database. How do I get all those Posts which are created in past 24 hours.
You can create a date range that consists of 24 hours in the following manner.
Using the momentjs library, you can create a date with the extension methods subtract() and cast it to a JS Date with the toDate() method:
var start = moment().subtract(24, 'hours').toDate();
or with plain vanilla Date objects, create the date range as:
var now = new Date(),
start = new Date(now.getTime() - (24 * 60 * 60 * 1000));
Use the where() method to use the query the Posts model using the above date range query, given the field which holds the timestamp is called date:
Posts.find()
.where({ "date" : { ">": start } })
.exec(function (err, posts) {
if (err) throw err;
return res.json(posts);
});

Compare date (moment.js) in MongoDB

I want to compare date from MongoDB and my date.
Also i read this and this post and I did not find an answer.
My Code :
today: function() {
var today = moment().format();
return Posts.find({createdAt : { $gte : today}}) // show posts created in "future" , so this function must return nothing
},
createdAt = moment().format();// in MongoDB
As a result this construction doesn't work, but if i compare lie this :
var today = moment().format();
var daystart = moment().startOf('day').format();
if (daystart > today){
console.log ("YES");
}
else if (daystart < today)console.log ("NO");
Return
"NO"
Anybody help ?
EDIT :
today: function() {
var today = moment().toDate();
var daystart = moment().startOf('day').toDate();
// console.log(today + daystart);
return Posts.find({createdAt : { $gt : today}})
},
week: function() {
var today = new Date();
return Posts.find({createdAt : { $lt : today}})
},
month: function() {
var today = new Date();
return Posts.find({createdAt : { $ne : today}})
}
createdAt = new Date();
The .format() method is a display helper function which returns the date string representation based on the passed token argument. To compare the date from MongoDB with the the current date and time, just call moment() with no parameters, without the .format() method and get the native Date object that Moment.js wraps by calling the toDate() method:
today: function() {
var now = moment().toDate();
return Posts.find({createdAt : { $gte : now }});
}
Convert date to MongoDB ISODate format in JavaScript using Moment JS
MongoDB uses ISODate as their primary date type. If you want to insert a date object into a MongoDB collection, you can use the Date() shell method.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:
new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
new Date("<YYYY-mm-ddTHH:MM:ss>") specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC.
new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
new Date() specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.
If you are writing code in JavaScript and if you want to pass a JavaScript date object and use it with MongoDB client, the first thing you do is convert JavaScript date to MongoDB date format (ISODate). Here’s how you do it.
var today = moment(new Date()).format('YYYY-MM-DD[T00:00:00.000Z]');
console.log("Next day -- " + (reqDate.getDate() + 1))
var d = new Date();
d.setDate(reqDate.getDate() + 1);
var tomorrow = moment(d).format('YYYY-MM-DD[T00:00:00.000Z]');
You can pass today and tomorrow object to MongoDB queries with new Date() shell method.
MongoClient.connect(con, function (err, db) {
if (err) throw err
db.collection('orders').find({ "order_id": store_id, "orderDate": {
"$gte": new Date(today), "$lt": new Date(tomorrow)}
}).toArray(function (err, result) {
console.log(result);
if (err) throw err
res.send(result);
})
})

How to save datepicker date as mongodb date?

In a meteor app I select a date via jquery datepicker, this is triggered by
click .tododateDue. After providing all information in my dialog all fields of the todo are saved via click .saveTodo
I like to display the date in my input field as dd.mm.yy but I need to save it in a mongodb collection as 'date'.
Since I use todo.datedue = tmpl.find('.tododateDue').value; to save the date I get a String in my collection.
How can I save this date as the type 'date' in the mongodb collection?
Template.todoDlg.events({
'click .saveTodo':function(evt,tmpl){
console.log('tmpl',tmpl);
var todo = {};
todo.note = tmpl.find('.todoitem').value;
todo.title = tmpl.find('.todotitle').value;
todo.datedue = tmpl.find('.tododateDue').value;
todo.project = Session.get('active_project');
Meteor.call('addTodo',todo);
Session.set('adding_todo',false);
},
'click .tododateDue': function (evt, tmpl) {
Meteor.setTimeout(function () {
$('.tododateDue').datepicker({
onSelect: function (dateText) {
console.log('date',tmpl.find('.tododateDue').value);
//Meteor.call('updateProjectDate', Session.get('active_project'), dateText);
},
dateFormat:'dd.mm.yy'
});
}, 100)
}
})
I think, you can use moment.js:
todo.datedue = moment(tmpl.find('.tododateDue').value, "dd.mm.yy").toDate();
It will return Date-object...
Perhaps autoform would help you here.
http://autoform.meteor.com/types