I am getting this error when just getting a document from the database and then immediately saving it. It is accepted on the initial insert though, and looks like the date fields are empty even though they are required.
{ stack: [Getter/Setter],
message: ‘Cast to date failed for value “[object Object]”‘,
name: ‘CastError’,
type: ‘date’,
value:
{ millisecond: 0,
second: 0,
minute: 0,
hour: 0,
day: 21,
week: 38,
month: 8,
year: 2011 } }
This is the schema and query code that fails:
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)});
});
});
}
Date.js is a very cool library, however the default implementation will create a mess in Node.js applications when working with MongoDB. I’d recommend you to use safe_datejs. You will be able to use Date.js function but you’re gonna have to convert the
Datevalues to a Date.js object before calling any of the Date.js magical functions.Example:
To change culture specific attributes, use
safe_datejs.DateType.CultureInfoMore info: https://github.com/firebaseco/safe_datejs