I've run into problem. I made field in my Mongoose schema with type "Date":
...
timeOfPassingQuestion: Date,
...
Now, I want to pass current time in hours, minutes, seconds and miliseconds and save it into that field. How should I format my Node variable so I can pass it without errors?
Edit: Also, I forgot to say that I wanna later see how much time user spent answering question by subtracting current time and time that I pulled from DB, timeOfPassingQuestion field.
This is the syntax to create a schema that supports a date field:
// Schema
{ //...
someDate: Date,
}
// date object that you can use whenever you decide to set it
var dateObj = new Date();
This will create a JavaScript date object that you can then pass into your Mongoose object for the date field.
Or, if you will always want it on creation, put it directly in your mongoose schema
{ //...
createdDate: { type: Date, default: Date.now },
}
In order to compare the time in the future, I suggest you use moment.js, then you can query the time difference like so:
moment(Model.createdDate).fromNow();
Sources:
Mongoose Schema
Moment.js fromNow
Related
I am using mongodb in my application to store data through nodejs . I have created a schema for a collection (to make it here easy I will call that collection register ) .Below is the structure of the collection' s schema .
const register_schema = new Schema(
{
arrived_at: { type: String }, // time of arrival
gone_at: { type: String } // time of departure
}
);
I want just to save time in the arrived_at and gone_at fields in the format of 'HH-MM-SS'. Is it possible to store such data in mongodb?
There is no fine datatype for time handling or for adding specific time in mongodb schema except the timestamp. For adding time, just use string to specify the timing you want to add.
I am trying to store default date and time using mongoose with the Node.JS but somehow, it is storing different time zone value in database. I'm using "MongoDB Atlas Database" as a DB server and also configured default time zone with reference to this. I have also tried this for change time zone and also tried "moment-timezone.js", But didn't get any luck.
I just want to store default date and time with Indian standard time format.
Following is my code for the schema.
const testSchema = new mongoose.Schema({
from: String,
to: String,
amount: Number,
message: {
type: String,
default: ""
},
creationdate: {
type: Date,
default: Date.now
}
});
Please help me with this issue. Show me the best way to solve this problem.
MongoDB stores Date fields as a UTC timestamp in milliseconds since the Unix epoch, which is a 64bit integer (53bit in JS). This is also what Date.now() is. There is no timezone component to the data by design.
If you need a consistent timezone format for a Date object, add a virtual field that returns the required timezone adjusted string or object from the date.
const testSchema = new mongoose.Schema({
creationdate: {
type: Date,
default: Date.now
}
});
testSchema.virtual('formattedCreationDate').get(function() {
return this.creationdate.toLocaleString(); // or day.js/luxon
});
If you need a timezone other than the user or system supplied value, store the required TZ data in another field and use that timezone field in the virtual formatting.
The virtual will probably be easier if you use day.js or luxon.
I have a mongoose document which has these properties:
DocSchema = new Schema({
issue_date: Date,
days_to_expire: Number
});
DocSchema.virtual.get(function () {
return moment(this.issue_date).add(this.days_to_expire, 'days');
});
I want to find all document that are to expire within a week, is this possible with this schema definition?
The operation I'm looking for is something like this:
today - (issue_date + days_to_expire) <= 7
How can I query something like that using mongoose?
You'll be saving yourself a lot of trouble if you just store the expiration date inside the document as well. Then you're looking at a simple find({ expiration_date: { $gte: today, $lte: todayPlusSeven } }). Otherwise you're left calculating the expiration date in an aggregation and matching based off that.
I want to show my blog posts, paginated by creation date. I will have a page for 5 posts written in 2012-10-01, a page for 11 posts written in 2012-10-03 and no page at all for 2012-10-02 (no posts written)
Each post document is stored with a creation date which is a datetime value, here's a mongoose snippet:
var postSchema = new Schema({
url: String,
creationDate: {type: Date, default: Date.now},
contenuto: String,
});
so it will have something like 2012-10-01 18:45:03... know what I mean.
In my code, I will create a
var searchDate = new Date(yy,mm,dd);
How can I use that for querying the posts collection, without considering the "time part" of creationDate?
I'm not sure this would always work:
Post.find({ creationDate:dataRicerca })
As per this post;
How do I resolve a year/month/day date to a more specific date with time data in MongoDB?
you can store the data separately (as well as the full date) in your schema for easier searching. You could also do this;
Post.find({Posted:{$gt: Date("2012-10-01"), $lt:Date("2012-10-02")}})
(updated to use Date() rather than ISODate() for better compatibility)
Suppose this is your model:
var EventSchema = new Schema({
title: String,
startDate: Date,
endDate: Date
});
I would like to throw in a date (as simple as like '24-12-2012') and then retrieve every event that started or proceeded at that single day.
How do you do that?
Sure:
First read up on mongo query syntax for dates, here is a how-to for date ranges: http://cookbook.mongodb.org/patterns/date_range/
Then translate that mongo syntax into mongoose.
Event.where('startDate').lte(yourDate).exec(callback); //should do the trick
Now you just need to parse date strings to javascript dates. There are some cool libraries to do that, I believe that moment.js won't have a problem with that date string.
Oh, I forgot the last bit of magic: Put that query into a static method attached to your Event model, so from now on you can just call
Event.earlierThan(yourDate, callback); //Where your custom static is called 'earlierThan'.