Sling Academy
Home/Node.js/Mongoose Exception: can’t convert from BSON type EOO to Date

Mongoose Exception: can’t convert from BSON type EOO to Date

Last updated: December 31, 2023

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.

Next Article: How to use geolocation in Mongoose (with examples)

Previous Article: How to prevent injection attacks in Mongoose

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates