MongoDB Mongoose storing same date and time - mongodb

I have a Uploads Schema where I have stored the uploaded file's date like:
uploaded_date: {
type: Date,
default: Date.now(),
}
By saving date as such, mongoose stores the date and time of files exactly the same. eg:
uploaded_date: 2020-05-19T08:10:00.034+00:00
when I upload multiple files within a minute or so. Why is this occuring? Should I use timestamp for differenciating times?

Use Date.now instead of Date.now()
Mongoose will replace Date.now with the current datetime when creating a new record, so it will update for every record. But, if you would use Date.now() your default value will be set to a fixed time(the creation time of your schema).
uploaded_date: {
type: Date,
default: Date.now,
}

Related

Automatically Delete a Token that was created after some milliseconds in Mongoose

I have the following Mongoose Model that I wish to auto-delete after 2mins. Unfortunately, the auto-delete is not working. Note that, I wish to keep the created_at field as a Number in milliseconds not as a date. How do I go about getting the below code to work for me.
const mongoose = require("mongoose");
const TokenSchema = new mongoose.Schema(
{
_id: mongoose.Schema.Types.ObjectId,
token: String,
deleted: Boolean,
deleted_at: Number,
created_at: { type: Number, expires: '2m', default: new Date().getTime() },//Auto-Delete after 2minutes
updated_at: Number,
}
);
TokenSchema.pre('save', function (next) {
let shadow = this;
let now = new Date().getTime();
shadow.updated_at = now;
if (!shadow.created_at) {
shadow.created_at = now;
}
next();
});
Thank you
Mongoose uses MongoDB TTL Indexes for expiring documents, which only functions on fields containing either a Date or array of Date values.
If the indexed field for a document contains any other type, it will not be automatically expired, so to get auto-expiry working, you will need to have created_at store type: Date.
MongoDB internally stores dates as the number of milliseconds since epoch, which you can extract with the valueOf() method, and the mongo query language permits querying a date field by pass a number of milliseconds.

How to get the BSON UTC datetime value?

I am learning the timeseries Database. I have created the Database in the mongoDb as a timeseries. Now when I am inserting the document then I am getting an error
'created_at' must be present and contain a valid BSON UTC datetime value
I am not able to understand how can I get this datetime. I have tried all format known to me but still I am getting the same error.
try setting timezone as UTC as :
DateTimeZone zone = DateTimeZone.UTC;
DateTimeZone.setDefault(zone);
You should try something like:
const schema = Schema(
{
timestamp: { type: Date, default: Date.now },
name: String,
metadata: Object
},
{
timeseries: {timeField: 'timestamp',
metaField: 'metadata',
granularity: 'hours'}
autoCreate: false,
});
// `Test` collection will be a timeseries collection
const Test = db.model('Test', schema);
See if works for you.
Mongoose Timeseries Docs

Is it valid practice to set an 'expire_at' field to null to cancel expiration in MongoDB?

I have a schema where I expire the document in 24 hours.
let mySchema = new Schema({
name: String,
createdAt: {type: Date, default: Date.now },
expire_at: {type: Date, default: Date.now, expires: 86400},
});
However, on some occasions I do not want to expire the document and then do myDocument.expire_at = null;
This seems to work and the document seems to not expire. However, are there better practices for achieving this or any problems that might occur if the document expiry is cancelled in this way?
Setting a field that has an ttl index on it to NULL to not have it expire is documented and thus a valid way to do it. You could also remove the entire field rather than setting it to NULL. (I'd prefer to keep the value; that way it's not ambiguous if the value is missing on purpose or not.)

How create a Date field with default value as the current timestamp in MongoDb?

How to create a date field with default value,the default value should be current timestamps whenever the insertion happened in the collection.
Thats pretty simple!
When you're using Mongoose for example, you can pass functions as a default value.
Mongoose then calls the function for every insertion.
So in your Schema you would do something like:
{
timestamp: { type: Date, default: Date.now},
...
}
Remember to only pass the function object itself Date.now and not the value of the function call Date.now()as this will only set the Date once to the value of when your Schema got created.
This solution applies to Mongoose & Node.Js and I hope that is your usecase because you did not specify that more precisely.
Use _id to get the timestamp.
For this particular purpose you don't really need to create an explicit field for saving timestamps. The object id i.e. "_id", that mongo creates by default can be used to serve the purpose thus, saving you an additional redundant space. I'm assuming that you are using node.js so you can do something like the following to get the time of particular document creation:
let ObjectId = require('mongodb').ObjectID
let docObjID = new ObjectId(<Your document _id>)
console.log(docObjID.getTimestamp())
And, if you are using something like mongoose, do it like this:
let mongoose = require('mongoose')
let docObjID = mongoose.Types.ObjectId(<Your document _id>)
console.log(docObjID.getTimestamp())
Read more about "_id" here.
When Creating Document, timestamps is one of few configurable options which can be passed to the constructor or set directly.
const exampleSchema = new Schema({...}, { timestamps: true });
After that, mongoose assigns createdAt and updatedAt fields to your schema, the type assigned is Date.
You would simply do this while inserting... for current timestamp.
collection.insert({ "date": datetime.now() }
Let's consider the user schema in which we are using created date, we can use the mongoose schema and pass the default value as Date.now
var UserSchema = new Schema({
name: {type: String, trim: true},
created: {type: Date, default: Date.now}
});
If we want to save timetamp instead of number then use Number isntead of number like that
var UserSchema = new Schema({
name: {type: String, trim: true},
created: {type: Number, default: Date.now}
});
Note:- When we use Date.now() in the default parameter then this will
only set the Date once to the value of when your Schema got created,
so you'll find the dates same as the that in the other document. It's better to use Date.now instead of Date.now().
Here's a command that doesn't set a default, but it inserts an object with the current timestamp:
db.foo.insert({date: new ISODate()});
These have the same effect:
db.foo.insert({date: ISODate()});
db.foo.insert({date: new Date()});
Be aware that Date() without new would be different - it doesn't return an ISODate object, but a string.
Also, these use the client's time, not the server's time, which may be different (since the time setting is never 100% precise).
I just wish to point out that in case you want the timestamp to be stored in the form of an integer instead of a date format, you can do this:
{
timestamp: { type: Number, default: Date.now},
...
}
Thanks friends ..
I found another way to get timestamp from _id field. objectid.gettimestamp() from this we can get it time stamp.
This is a little old, however I fount when using the Date.now() method, it doesn't get the current date and time, it gets stuck on the time that you started your node process running. Therefore all timestamps will be defaulted to the Date.now() of when you started your server.
One way I worked around this was to do the following:
ExampleSchema.pre('save', function (next) {
const instanceOfSchema = this;
if(!instanceOfSchema.created_at){
instanceOfSchema.created_at = Date.now();
}
instanceOfSchema.updated_at = Date.now();
next();
})
createdAt: {type: Date, default:Date.now},

MeteorJS & Collection2. How to create Schema with data of type 'Time'?

Hi I'm trying to create a MongoDB Collection with a Collection2 schema connected to an Autoform (specifically a Quickform if possible) That allows me to store a time and date, not just a date.
For a date, the JSON validation is type: Date, - is there a type: Time?
Or another way to insert a date/time picker into an autoform and save it to a Collection2 Schema Collection?
Thanks for any help or hints pointing to similar problems.
Turns out I was just being stupid.
type: Date
is still correct as Blakes Seven 7 pointed out (thanks).
There is a package called aldeed:autoform-bs-datetimepicker which you need to add to your Meteor app to include the datetime picker in your quickform/autoform.
a sample schema which works is then:
{
typeTest: {
type: Date,
optional: true,
autoform: {
afFieldInput: {
type: "bootstrap-datetimepicker"
}
}
}
}