2017-04-20 33 views
0

我有一個數據庫posts。對於每個post,我想保存不同用戶的最後打開時間。因此,我決定在後端保存絕對時間(即moment())並在前端顯示相關時間(即,通過fromNow(),例如2 days ago)。在後臺記錄絕對時間並在前端顯示相關時間

在後端:

var PostSchema = new mongoose.Schema({ 
    ... ... 
    lastOpens: { type: Array, default: [] }, 
}); 

PostSchema.methods.updateLastOpens = function (userId, cb) { 
    ... ... 
    this.lastOpens.push({ time: moment(), userId: userId }); 
}; 

在前端:

alert(JSON.stringify(post.lastOpens[j].time)) 
var x = post.lastOpens[0].time.fromNow() 

然而,在前端的第一行顯示了很長的對象{"_isValid":true,"_d":"2017-04-20T02:42:50.932Z","_locale":{"_dayOfMonthOrdinalParseLenient":{},...。第二個像TypeError: post.lastOpens[0].time.fromNow is not a function

有誰知道哪裏錯了,怎麼做到這一點?

+0

你推moment.js對象到數組,然後字符串化了,所以你看到的是串化的時刻對象,而不是日期。你應該推''time:moment()。fomat('YYYY-MM-DD'),...}或類似的。 – RobG

+0

我在'alert()'中進行了字符串化處理,但沒有在'var x = post.lastOpens [0] .time.fromNow()'中進行處理。 – SoftTimur

+0

是的,但是你應該考慮的是後端將序列化對象,因此你看到的是長Json,並將它發送到前端。當它到達前端時,它不再是一個時刻對象。它是一個普通的json對象,它有數據但沒有方法。我會從前端的.time內容重新創建時刻(),然後重試代碼。 – Reza

回答

0

您從後端獲得的數據可能不是moment object。因此你無法致電fromNow功能。要調用fromNow,您可以將數據轉換爲一個時刻對象由moment constructor通過_d,然後調用fromNow該對象在這樣

var x = moment(post.lastOpens[j].time._d).fromNow() 
相關問題