我的目標是更新itemSchema中每個對象的timeleft
字段。如何更新mongodb中的字段?
const ItemSchema = mongoose.Schema({
name: String,
time: { type: Date, default: Date.now },
timeleft: { type: Number, default: 24 }
});
例如爲了讓我在ItemSchema
ItemSchema.methods.calculateTime = function() { // Done check it one hour
var currentTime = moment() // Get current Time
var timeStored = moment.utc(this.time).local().format(); // Convert this.time UTC to local time
var timeDiff = currentTime.diff(timeStored, 'h'); // See the difference in time example - 7
this.timeleft -= timeDiff; // Deduct timeleft witht he timeDiff , result would be 17
this.save(); // Simple save it to the database
}
API例如更新每個對象
app.get('/allItems', function(req, res) {
Item.find({}, function(err, items) {
// I want to run items.calculateTime(); but it is not possible.
// How would I run calculateTime function on the array of objects?
});
});
我的目標是繼續檢查的時間差,並把它保存到剩餘時間
數據示例
timeleft: 24
// after calculateTime
time: 17
Because I want to show this to the User
// 17 hours left
我該如何做到這一點的對象數組,而不是單個對象?
看看你的用例,我不會將這個值保存到數據庫中,而是在查詢時動態計算它。看看Mongoose的虛擬獲得者。 – qqilihq
所以數據不會被保存到'timeleft'字段? – sinusGob
是的。據我瞭解,它可以從'時間'屬性計算,對吧? – qqilihq