How create a Date field with default value as the current timestamp in MongoDb? - 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},

Related

How to use Object type in mongose schema?

I am trying to store the amount of time an employee has worked in my MongoDB database, but not able to make a mongoose schema whose type will object.
The desired database should have a document like this:
{
name: 'name of employee',
report: {'01-01-2023':5hr, '02-01-202':7hr, '03-01-2023':8hrs}
}
This report will contain an object whose key will be a date and the value will be minutes or hours an employee has worked on that date.
how can I make a schema to achieve the desired goal, I have tried like this but did not work.
const UserSchema = new mongoose.Schema({
name:{
type: String,
required: true
},
report: {
type: Object, // what should I write here
}
})

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.

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

MongoDB Mongoose storing same date and time

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,
}

Mongoose mixed SchemaType

I couldn't understand that for what purpose mongoose schemaType is used for. If someone could explain it will be helpful.
I'm have to reference another schema from a schema i want to know if we can get the details of all schema together when we do a findOne() on mongoose.
mixed schema means whatever you want the type to be. if you input a String, Number, Date, mongoose will let you do that. However according to documentation, mongoose ref does not work with mixed.
Note: ObjectId, Number, String, and Buffer are valid for use as refs.
if you use mixed, and ref it, you won't be able to query it back.
If you start all over(delete the database and reinsert again), use ObjectId instead of Mixed.
var storySchema = Schema({
author : { type: ObjectId, ref: 'Person' },
});
If you wish to retain old database, the best way is to change mixed to string
var storySchema = Schema({
author : { type: String, ref: 'Person' },
});