Encountering data type conversion errors in Mongoose can be perplexing and frustrating. This tutorial dives into the ‘can’t convert from BSON type EOO to Date’ exception and offers solutions.
Understanding the Error
The error occurs when Mongoose tries to cast a value to a Date object, but encounters a ‘null’ or missing field instead. Let’s examine an example schema.
const mongoose = require('mongoose');
const { Schema } = mongoose;
const eventSchema = new Schema({
eventDate: Date
});
Let’s Fix It
Basic Troubleshooting
Ensure that the date field is not null during insertion and conforms to the ISO date format accepted by JavaScript’s Date
object.
const Event = mongoose.model('Event', eventSchema);
Event.create({ eventDate: new Date() })
.then(event => console.log(event))
.catch(err => console.error(err));
Dealing with Null Values
Provide default values or validate the data before insertion to handle null effectively.
eventSchema.path('eventDate').validate(
date => date != null,
'eventDate cannot be null'
);
Advanced Data Handling
Implement pre-save hooks to manage complex date operations prior to saving a document.
eventSchema.pre('save', async function (next) {
if (!this.eventDate) {
this.eventDate = new Date();
}
next();
});
Using Custom Casters
Create custom caster functions for handling ambiguous date inputs safely.
const safeDateCaster = val => val ? new Date(val) : null;
mongoose.Schema.Types.Date.cast(safeDateCaster);
Inspecting Database Values
Perform regular database inspections to ensure that no corrupt or null date values exist that may trigger this exception.
Conclusion
This error has various sources but by validating data, providing default values and using custom casters, developers can ensure type safety in their Mongoose schemas.