【发布时间】:2017-01-15 18:13:02
【问题描述】:
我的目标是更新 itemSchema 中每个对象的 timeleft 字段。
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 的虚拟吸气剂。
-
所以数据不会保存到
timeleft字段? -
是的。据我了解,是可以从
time属性算出来的吧? -
时间是日期类型,我之所以添加
timeleft,是为了以后可以根据timeleft字段查询 -
例如,如果
timeleft是0,则不要向用户显示此内容。