user3310334
user3310334

Reputation:

Prevent only undefined values

In mongoose I can set required: true to block ... falsey? values.

But I want to allow '', [], 0, null, and only block undefined.

How can I do this?

const MySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  }
});

I want to allow document.name to be null.

Upvotes: 0

Views: 84

Answers (1)

Paul
Paul

Reputation: 141829

To prevent undefined, while still allowing null you can just use a custom validator:

const MySchema = new mongoose.Schema({
  name: {
    type: String,
    validate: {
      validator: v => v !== undefined,
      message: 'name is required',
    },
  }
});

Upvotes: 1

Related Questions