Using MongoDB in node. JS is a mongoose.
Suppose there is a definition of the following mongoose schemas:
var New Mongoose. Schema ({ biz:string, name:string, tradetype:string, totalfee:number, transactionid:string, createtime: { type:date, default: Date.now }, updatetime: { Type:date, default: Date.now }}, { false});
We want to save the model data without specifying the value of the createtime field, and according to the schema above,Createtime is automatically saved as the current time of the system. Of course, the value of the updatetime field can be automatically saved as the current time of the system when updating the model data. But here are two questions:
1. A field with the default attribute in the schema definition automatically generates a value when a new document is created, but if the field is missing from the database, the value is automatically generated when the data is read. For example, a previously saved document in a table defined by the above schema if there is no createtime field, the value of the createtime field when reading the data is the system current time by default. This shows unscientific.
2. We are not able to automatically update the value of the updatetime field every time the document is updated, so it is a bit superfluous to set the default property for the updatetime field.
How can you let MongoDB automatically generate and manage the values of the createtime and updatetime fields in the schema definition? The answer is to use the timestamps option. The role of the timestamps option can be seen in the interpretation of official documents Http://mongoosejs.com/docs/guide.html#timestamps
We modify the definition of the above schema as follows:
var Itemschema = new Mongoose. Schema ({biz:string, name:string, tradetype:string, Totalfee:number, transactionid:string, Createti Me: {type:date, default : date.no W}, UpdateTime: {type:date, default : Date.now}}, {versionkey: false timestamps: {createdat: ' Createtime ', Updatedat: ' UpdateTime ' } });
Added highlighted sections. The timestamps option automatically generates the createat and updateat two fields when the document is created, and the value is the current time of the system. and automatically updates the value of the updateat field when the document is updated to the current time of the system. If you want to customize the names of these two fields, you can use the definition method for the highlighted section above. If you use the default field name, you can use the following definition method:
True
In Mongoose, the use of the timestamps option when defining the database model schemas can bring us a lot of convenience. Instead of specifying the value of the createtime field in your code when you create a document, you do not have to modify the value of the updatetime field when you update the document.
Mongoose of the timestamps option in schemas definition