2011-09-23 109 views
0

我剛剛從數據庫中獲取文檔並立即保存時出現此錯誤。儘管它在初始插入時被接受,並且看起來像日期字段是空的,即使它們是必需的。貓鼬/ mongodb日期保存castError

{堆棧:[的getter/setter], 消息: '投射迄今失敗值 「對象的對象]」', 名: 'CastError', 類型: '日期', 值: {毫秒:0, 第二:0, 分鐘:0, 小時:0, 天:21, 周:38, 月:8, 年:2011}}

這是架構和查詢代碼失敗:

var Event = new Schema({ 
    id  : { type: String, index: true } 
    , msg  : { type: String, lowercase: true, trim: true } 
    , triggerOn  : { type: Date, required: true } 
    , createdOn  : { type: Date, required: true } 
    , triggered  : { type: Boolean, required: true } 
}); 

exports.pullAndUpdateTest = function(){ 
    var Model = mongoose.model('Event'); 
    Model.find({ triggered: false }, function (err, docs) { 
     if (err){ 
      console.log(err); 
      return; 
    } 
    docs.forEach(function(doc, index, array){ 
     //date both appear to be null here 
       console.log(doc.triggerOn); //=> null/prints blank 
     console.log(doc.createdOn); //=> null/prints blank 

     doc.triggered = true; 
     doc.save(function(err){ console.log(err)}); 
    }); 
}); 
} 
+0

還發現[此](https://github.com/LearnBoost/mongoose/問題/ 502)從未解決的確切問題 –

+0

文檔的輸出是什麼? –

+0

最新版本的貓鼬修復了這個問題 –

回答

1

Date.js是一個非常酷的庫,但是在使用MongoDB時,默認實現會在Node.js應用程序中創建一個混亂。我建議你使用safe_datejs。您將能夠使用Date.js函數,但在調用任何Date.js神奇函數之前,您必須將Date值轉換爲Date.js對象。

實施例:

var safe_datejs = require('safe_datejs'); 
var today = new Date(); 
var unsafeToday = today.AsDateJs(); // Converting to Date.js object 
var unsafeTomorrow = unsafeToday.clone().add({days:1}); // Work with Date.js a little 
var tomorrow = unsafeTomorrow.AsRegularDate(); //converted back safe to be used with MongoDB 

要更改特定文化的屬性,可以使用safe_datejs.DateType.CultureInfo

更多信息:https://github.com/firebaseco/safe_datejs

+0

Date.js實際上在保留原始Date模型的同時還添加了其他行爲很不錯。問題是,當Mongoose在對象上找到一個toObject方法時,它當前會跳過類型檢查。有一個pull請求正在等待糾正:https://github.com/LearnBoost/mongoose/pull/646。 –

0

您是否用貓鼬定義了您的模型?

var Model = mongoose.model('Event', Event); 
+0

我有,謝謝。 –

1

此,如果你在你的應用程序的任何地方需要datejs會發生(或使用任何模塊,反過來,需要datejs)。

+0

不再如此 - 最新版本的貓鼬已經修復。 –