本文轉自:http://www.cnblogs.com/jaxu/p/5595451.html
在Node.js中使用MongoDB少不了Mongoose。假設有如下Mongoose Schemas的定義:
var ItemSchema = 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 } }, { versionKey: false });
我們希望在保存model數據時不用指定createTime字段的值,按照上述Schema的定義,createTime會自動保存為系統當前時間。當然,在更新model數據時updateTime字段的值也能自動保存為系統當前時間。但是這里有兩個問題:
1. Schema定義中含有default屬性的字段在創建新文檔時會自動生成值,但是如果數據庫中缺少該字段,讀取數據時也會自動生成值。例如上述schema所定義的表中先前保存進去的文檔如果沒有createTime字段,則讀取數據時createTime字段的值默認都是系統當前時間。這顯示不科學。
2. 我們並不能做到在每次更新文檔時自動更新updateTime字段的值,所以這里給updateTime字段設置default屬性有點多余。
那如何才能在schema定義中讓MongoDB自動生成和管理createTime和updateTime字段的值呢?答案是使用timestamps選項。有關timestamps選項的作用可以看官方文檔的解釋http://mongoosejs.com/docs/guide.html#timestamps
我們將上述Schema的定義修改如下:
var ItemSchema = 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 } }, { versionKey: false, timestamps: { createdAt: 'createTime', updatedAt: 'updateTime' } });
添加了高亮顯示的部分。timestamps選項會在創建文檔時自動生成createAt和updateAt兩個字段,值都為系統當前時間。並且在更新文檔時自動更新updateAt字段的值為系統當前時間。如果想自定義這兩個字段的名稱,則可以使用上述高亮部分的定義方法。如果使用默認的字段名,則使用下面的定義方法即可:
timestamps: true
在Mongoose中,定義數據庫model schemas時使用timestamps選項可以給我們帶來許多便利。在創建文檔時不用在代碼中去指定createTime字段的值,在更新文檔時也不用去修改updateTime字段的值。