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

天大地大妈咪最大 提交于 2019-12-06 19:22:00

问题


How to create a date field with default value,the default value should be current timestamps whenever the insertion happened in the collection.


回答1:


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.




回答2:


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.




回答3:


You would simply do this while inserting... for current timestamp.

collection.insert({ "date": datetime.now() } 



回答4:


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.




回答5:


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



回答6:


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




回答7:


Thanks friends .. I found another way to get timestamp from _id field. objectid.gettimestamp() from this we can get it time stamp.




回答8:


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



回答9:


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



来源:https://stackoverflow.com/questions/36550263/how-create-a-date-field-with-default-value-as-the-current-timestamp-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!