Unknown
Unknown

Reputation: 423

Mongoose partial validations

I have this schema for mongoose

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const Person = new Schema({
first_name: {
    type: String,
    required:true
},
last_name: {
    type: String,
    required:true
},
dob: {
    type: Date
},
phone: {
    type: String
},
email: {
    type: String,
    required:true
},
address: {
    type: String,
    required:true
},
city: {
    type: String
},
state: {
    type: String
},
zipCode: {
    type: Number
}
});
module.exports = mongoose.model("Person", Person);

My App user needs to fill 2 forms for this information. Half information like first_name,last_name,dob,phone will be in first form. I have to save this info first and then move to second form and on second form I have email,address,city,state,zipcode.

But when I save first form. It will give me Error because Email is required and which is on second form.

So How can I validate some fields which are in object using mongoose?

Or is there any other solution?

Thanks

Upvotes: 1

Views: 398

Answers (1)

André Adriano
André Adriano

Reputation: 419

You can use a function on the required field in order to test if the first_name field is not empty, otherwise, the email field should not be required.

Something like this:

const Person = new Schema({
first_name: {
    type: String,
    required:true
},
last_name: {
    type: String,
    required:true
},
dob: {
    type: Date
},
phone: {
    type: String
},
email: {
    type: String,
    required: () => this.first_name != null
},
address: {
    type: String,
    required: () => this.first_name != null
},
city: {
    type: String
},
state: {
    type: String
},
zipCode: {
    type: Number
}
});

Documentation

Upvotes: 1

Related Questions