Skip to content

Does Mongoose auto cast types?

When I retrieve and modify a Lobby with this Schema it seems to automatically cast types. I could not find the documentation for that feature so I am wondering if I am mistaken something else for autocasting.

I convert the types of password and owner to true or false because this is an exposed API endpoint everyone can view.

When I run the anonymizer function it runs and results in password : "true" not password: true. I would like it to send password: true but I am not sure if that is possible.

// Schema
const LobbySchema = new mongoose.Schema({
  name: String,
  password: String,
  owner: { type: String, require: true },
  Player: [],

// Anonymizer function
lobby.password = !!lobby.password;
lobby.owner = lobby.owner === user ? true: false;



Yes, Mongoose cast values if it is possible.

The problem here is your schema define type owner as String. So the value true or false will be casted to string.

This is why you get password : "true".

To get password as a boolean you can either set Boolean into the schema or use Custom casting

Not tested but following the documentation should be similar to this:

const originalCast = mongoose.Boolean.cast();
mongoose.Boolean.cast(v => {
  if (v === 'true') {
    return true;
  if (v === 'false') {
    return false;
  return originalCast(v);