如何在 MongoDb 中创建一个默认值作为当前时间戳的日期字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36550263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How create a Date field with default value as the current timestamp in MongoDb?
提问by Jagadeesan G
How to create a date field with default value,the default value should be current timestamps whenever the insertion happened in the collection.
如何创建具有默认值的日期字段,只要在集合中发生插入,默认值应该是当前时间戳。
回答by Joschua Schneider
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.
这很简单!例如,当您使用 Mongoose 时,您可以将函数作为默认值传递。Mongoose 然后为每次插入调用该函数。
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.
请记住只传递函数对象本身Date.now
而不是函数调用的值,Date.now()
因为这只会将 Date 设置为创建架构时的值。
This solution applies to Mongoose & Node.Js and I hope that is your usecase because you did not specify that more precisely.
此解决方案适用于 Mongoose 和 Node.Js,我希望这是您的用例,因为您没有更准确地指定它。
回答by UtkarshPramodGupta
Use _idto get the timestamp.
使用_id获取时间戳。
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:
出于这个特殊目的,您实际上并不需要创建一个显式字段来保存时间戳。对象 id 即"_id"
mongo 默认创建的可用于达到目的,从而为您节省额外的冗余空间。我假设您正在使用 node.js,因此您可以执行以下操作来获取特定文档创建的时间:
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:
而且,如果您使用的是mongoose之类的东西,请这样做:
let mongoose = require('mongoose')
let docObjID = mongoose.Types.ObjectId(<Your document _id>)
console.log(docObjID.getTimestamp())
Read more about "_id"here.
在此处阅读有关“_id”的更多信息。
回答by Thalaivar
You would simply do this while inserting... for current timestamp
.
您只需在插入... for current 时执行此操作timestamp
。
collection.insert({ "date": datetime.now() }
回答by sultan aslam
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.
之后,猫鼬将 createdAt 和 updatedAt 字段分配给您的架构,分配的类型是日期。
回答by VIKAS KOHLI
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
让我们考虑使用创建日期的用户模式,我们可以使用猫鼬模式并将默认值作为 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
如果我们想保存时间戳而不是数字,那么像这样使用 Number istead of number
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().
注意:- 当我们在默认参数中使用 Date.now() 时,这只会将 Date 设置为创建架构时的值一次,因此您会发现日期与其他文档中的日期相同。最好使用 Date.now 而不是 Date.now()。
回答by Chong Lip Phang
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},
...
}
回答by jcsahnwaldt says GoFundMonica
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.
请注意,Date()
没有new
会有所不同——它不返回一个ISODate
对象,而是一个字符串。
Also, these use the client's time, not the server's time, which may be different (since the time setting is never 100% precise).
此外,这些使用客户端的时间,而不是服务器的时间,这可能会有所不同(因为时间设置永远不会 100% 精确)。
回答by Jagadeesan G
Thanks friends .. I found another way to get timestamp from _id field. objectid.gettimestamp() from this we can get it time stamp.
谢谢朋友.. 我找到了另一种从 _id 字段获取时间戳的方法。objectid.gettimestamp() 从中我们可以得到它的时间戳。
回答by J.Wolfe
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:
这有点旧,但是我发现在使用 Date.now() 方法时,它没有获取当前日期和时间,它会在您开始运行节点进程时卡住。因此,所有时间戳都将默认为您启动服务器时的 Date.now()。我解决此问题的一种方法是执行以下操作:
ExampleSchema.pre('save', function (next) {
const instanceOfSchema = this;
if(!instanceOfSchema.created_at){
instanceOfSchema.created_at = Date.now();
}
instanceOfSchema.updated_at = Date.now();
next();
})