mongoose Schema max property has no effect

Issue

const mongoose = require("mongoose");

const PostSchema = new mongoose.Schema(
  {
    user_id: {
      type: String,
      required: true,
    },
    content: {
      type: String,
      max: 150,
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

As defined above, I can nevertheless push content that has more than 150 characters. What is wrong with how the Query is defined?

Solution

Type string does not have “max”, instead use “maxLength”:

maxLength: 150,

Documentation about validation that mentions this.

Hopefully that helps!

Answered By – Alexander Staroselsky

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published