Matt Leach
Matt Leach

Reputation: 979

NodeJS saving date to MongoDB using Moment

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.

Upvotes: 1

Views: 6191

Answers (2)

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

Upvotes: 0

clouds8
clouds8

Reputation: 41

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()

Upvotes: 4

Related Questions