2016-09-14 40 views
7

模式:的MongoDB /貓鼬時間戳更新不及時

var schema = new Schema({...}, { 
    timestamps: true, 
    id: false, 
    toJSON: { 
     virtuals: true, 
    }, 
    toObject: { 
     virtual: true, 
    } 
}); 
schema.virtual('updated').get(function() { 
    if(typeof this.updatedAt === "undefined" && typeof this.createdAt === "undefined") return ""; 
    var updated = (typeof this.updatedAt === "undefined") ? this.createdAt : this.updatedAt; 
    return "Updated "+moment(updated).fromNow(); 
}); 

此代碼最近的工作 - 爲某個特定的實例updatedAt出現在8月24日,但任何新的編輯文檔更新時間戳。

感覺就像我在這裏錯過了一些非常愚蠢的東西。

+0

你能檢查type.of this.updatedAt嗎? – abdulbarik

+0

@abdulbarik typeof league.updatedAt => object –

+0

我複製粘貼你的代碼並運行在我的服務器上,它與貓鼬4.6.1一起工作得很好,所以你可能錯過了別的地方。 請提及您正在使用的貓鼬版本,或任何貓鼬插件。 –

回答

0

您比較objectString,這就是爲什麼條件false總是

schema.virtual('updated').get(function() { 
    if(typeof this.updatedAt === undefined && typeof this.createdAt === undefined) return ""; 
    var updated = (typeof this.updatedAt === undefined) ? this.createdAt : this.updatedAt; 
    return "Updated "+moment(updated).fromNow(); 
}); 

試試這個,它應該工作

+0

感謝您的回答,但似乎問題並沒有成爲的那部分 - 問題與updatedAt時間戳不更新的編輯。 –

+0

是否意味着您的狀況良好? – abdulbarik

+0

你卡在哪個地方? – abdulbarik

2

可以嘗試通過修改您的模式,如:

var schema =new Schema({..}, 
      { timestamps: { createdAt: 'createdDate',updatedAt: 'updatedDate' } 
}); 

爲此架構時間戳將在save()update()findOneAndUpdate() 。所以沒必要schema.virtual('updated')...

過程-2

添加createdDateupdatedDate與架構中的Date類型和更新使用模式插件這些日期字段。

,如:

var mongoose = require('mongoose'), 
    Schema = mongoose.Schema, 
    SchemaPlugin = require('../helpers/schemaPlugin'); 
    var schema =new Schema({..}, 
    createdDate: { 
     type: Date, 
     default: Date.now 
    }, 
    updatedDate: { 
     type: Date, 
     default: Date.now 
    } 
    }); 

    schema.plugin(SchemaPlugin); 

schemaPlugin.js文件:

module.exports = function(schema) { 

    var updateTimestemps = function(next){ 
    var self = this; 


    if(!self.createdAt) { 
     self.createdDate = new Date(); 
     //or self.update({},{ $set: { createdDate : new Date(), updatedDate: new Date() } }); 
    } else { 
     self.updatedDate= new Date(); 
     //or self.update({},{ $set: {updatedDate: new Date() } }); 
    } 
    next(); 
    }; 

    schema. 
    pre('save', updateTimestemps). 
    pre('update', updateTimestemps). 
    pre('findOneAndUpdate', updateTimestemps); 
}; 
1

updatedAt和createdAt都在同一時間創建時使用貓鼬被輸入到數據庫中的一個新的文檔,你的檢查是否updatedAt是未定義或不是不合邏輯的,因爲在創建新文檔時兩者都具有相同的值。

無論您何時使用貓鼬更新函數或findByIdAndUpdate或findOneAndUpdate,updatedAt的值都會自動更新。使用Mongodb客戶端(如mongochef或robomongo)直接檢查updatedAt的值。