I'm trying to save a date to MongoDB using MomentJS. I want to save the current date/time plus 1 hour. To do this I use the following code (I'm using seconds as this number will be pulled from an API which gives a number in seconds, once I get the basics sorted I will change the 3600 to a variable):
var expire = moment().add(3600, 's').format();
User.update({email: req.user}, {$set: {expire: expire}}, function(err, update) {
if(err) throw err;
});
If I console.log the value for expire it shows the time with 1 hour added as expected. The issue is that what it saved in my DB is the current time WITHOUT the hour added to it.
Any help would be greatly appreciated.
In mongodb, the comparing time is supposed to use utc time and Date obj.
Because var expire = moment().add(3600, 's').format(); return a string not obj.
You should transform it to a Date obj so that mongodb can know it.
What you have to do is very easy.
var expire = moment().add(3600, 's').format().toDate()
In fact, if you want to compare time in mongo with gt and lt , I suppose you change the time to utc. let time = moment().utc(yourTime, "YYYY-MM-DD HH:mm:ss").toDate()
Tell mongoDB about the change by using doc.markModified('pathToYourDate').
const Assignment = mongoose.model('Assignment', { dueDate: Date });
Assignment.findOne(function (err, doc) {
doc.dueDate.setMonth(3);
doc.save(callback); // THIS DOES NOT SAVE YOUR CHANGE
doc.markModified('dueDate');
doc.save(callback); // works
})
See full details here: https://mongoosejs.com/docs/schematypes.html#dates
Related
I have a pub/sub function running which when triggered, fetches all documents from a Firebase collection where date is today.
Tested the code in a local (non-pubsub) node environment and works perfectly, but when published, it cannot find any documents, but can in the local version.
I'm guessing it's something to do with date passed, but I can't see why it would work locally but not in this pub/sub function?
export const check_orders = functions.pubsub.schedule('0 9 * * *').timeZone('Europe/London').onRun(async context => {
const currentDate = moment();
currentDate.set({hour: 0, minute: 0, second: 0, millisecond: 0});
console.log('currentDate:', currentDate);
const toDate = currentDate.toDate();
console.log('toDate:', toDate);
const currentDateTimestamp = admin.firestore.Timestamp.fromDate(currentDate.toDate());
console.log('currentDateTimestamp:', currentDateTimestamp);
const query = db.collection('orders').where('delivery.delivery_due', '==', toDate).where('user_status', '==', 'active');
const tasks = await query.get();
...
}
When this is triggered, currentDate will log: moment("2020-05-01T00:00:00.000")
I have also tried adding toDate() to currentDate which will log 2020-05-01T00:00:00.000Z. Also is unable to find any documents.
Added another test to convert the date to a Firebase timestamp which outputs Timestamp { _seconds: 1588291200, _nanoseconds: 0 }, but still does not fetch any documents.
If I loop through the above code in the local test, I would get back 1 document, but the pub/sub will not return any. Tested removing only fetching documents where status = active and it's successful, so it's for certain to do with the date.
The test document delivery_due date is set to today and the user_status is set to active, so the data in the document is as expected.
Am I missing something?
You have a problem with timezone differences. Your date from moment is measured at UTC (that's what the "Z" means at the end of the logged currentDate string), but your date in the timestamp field is measured at UTC+1. They are both saying "midnight", but since they are in different timezones, they are not referring to the same moment in time, so your query does not match.
You will need to take some care to make sure the exact same moment in time is being used in both the query and the document. I suggest also taking a look at the code that inserts the date in the timestamp to get it to match what the query wants.
Let's say i am storing some timestamps in my MongoDB, each timestamp indicates a time when some certain function should be run.
I am not sure what should be the correct approach to this since I am new in backend developing.
Mongo data structure goes like this(this is just an example):
{id: 115155, userId: 152115, timestamp: 13-09-2019:15:30:00}
and on this certain time I want to trigger a function:
someFunction(eventId, userId){ ...something here }
You need to change the format of timestamp you get from mongodb into something like this - "13 Sept 2019 18:39:40" or "2019-01-01 00:00:00". Then you need to parse the timestamp you get from mongodb using this Date.parse()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Once that is done you need to get difference between timestamp and current time and use that difference in a setTimeout() function, which takes 2 parameters - function to be run and time in milliseconds
let timediff = new Date() - Date.parse("2019-09-13 18:54:50");
setTimeout(function() {
console.log("Called when current time = mongodb timestamp");
}, timediff);
I have the code below updating offers_status to 'expired' if date stored on a mongodb database is old than current system/server time;
dbo.collection("offers").updateMany({older_date_in_DB:{$lt: current_system_time},
{$set:
{offerStatus:"EXPIRED"}},
(err,response)=>{
if(err) throw err;
console.log(response.modifiedCount)
})
However, i notice that if the current date is say 10/18/2019 and older_date_in_db is say 08/01/2019,the query above doesn't update the offer status to 'EXPIRED'. I don't understand why?
A date like 10/15/2019 updates the status to "EXPIRED" while a date like "08/01/2019" doesn't.
Please use following line for compare date condition in mongodb
{ older_date_in_DB: { $lt: new Date('10/18/2019') } }
if value is dateFormat then use new keyword
I am new to loopback. I have a date column start_date with DATE datatype.
when i try to fetch data with greater than or less than operations on start_date is working, but when i tried to fetch data equal to a date its not working:
the following is my fetching part:
Its working:
app.models.goals.find({where: {
start_date: {gt:'2016-03-31'}
}}, function(err, res) {
});
Its not working:
app.models.goals.find({where: {
start_date: '2016-03-31'
}}, function(err, res) {
});
Data is there in DB for 2016-03-31, but empty response. Is any syntax error.please help me to solve this.
I don't think there is anything wrong with the syntax. I tried the same syntax in both Strongloop API Explorer and with loopback Node.JS API and found it to be working.
However, While checking these out, I noticed that when the date string doesn't have time and TZ information in it, the time portion is assumed to be 00.00.00 in the local timezone. For example, when I used the following code on my "Sandbox" model:
Sandbox.find({where: {myDateProp:'2016-04-2'}}, function(err, res){
console.log('results are %j', res);
next();
});
The retrieved results record contained:
Retreived results are [{"myStringProp":"String5","myDateProp":"2016-04-01T18:30:00.000Z","id":"56fc1dc6b9de1a6b06750b98"}]
Notice that my search for 2016-04-2 actually matched a record with date 2016-04-01 6:30 PM which is the GMT equivalent of 2016-04-2 00:00:00 IST.
I am guessing that this may have something to do with the behaviour that you observe. I'd recommend you to check the Date value of start_date of the record in the database. Then, if necessary add the time and timezone information to the filter in your code.
I have a Node.js application and I'm using Mongoose to interface with MongoDB on Compose.io. Here's some code that should store the current date and time in my database:
signup.Volunteer.find({_id : uniqueid.toObjectId()}, function(err, doc){
var volunteer = doc[0];
var date = new Date();
console.log(date.toString());
//volunteer.time_out is an array
//defined in Volunteer Schema as: 'time_in : [Date]'
volunteer.time_in = volunteer.time_in.push(date);
volunteer.save(function(err){
...
});
});
....
If I print these date objects to the console, I get the right date. BUT, when I store the object in my database, it's stored as "1970-01-01T00:00:00.001Z". Is there any idea why this would be happening?
The problem is that you're assigning the return value of volunteer.time_in.push back to volunteer.time_in. The return value is the new length of the array, not the array itself.
So change that line to just:
volunteer.time_in.push(date);
Check the date format in your database. MongoDB date format is YYYY-MM-DD