mongoose / mongodb date save castError
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 Date
values to a Date.js object before calling any of the Date.js magical functions.
Example:
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
To change culture specific attributes, use safe_datejs.DateType.CultureInfo
More info: https://github.com/firebaseco/safe_datejs
This will occur if you have datejs required anywhere in your application (or use any module that, in turn, requires datejs).
Have you defined your model with mongoose?
var Model = mongoose.model('Event', Event);
精彩评论