What does validateSync do?

tdd

#1

Question

What does validateSync do?

Answer

It executes all registered validation rules for a document, skipping all asyncronous ones, for example calling validateSync() on a document created from this schema:

const gameSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        minlength: 4,
        maxlength: 200
    },
    publisher: String,
    tags: {
        type: [String],
        validate: {
            validator: function (v) {
                return v.length > 1
            },
            message: 'You must provide more than 1 tag.'
        }
    },
    date: { type: Date, default: Date.now },
    onSale: Boolean,
    price: {
        type: Number,
        required: function () { return this.onSale }
    }
});

would check if title exists, that it is at least 4 characters and no more than 200, that tags has at least one, and that price exists if onSale is true. Under those conditions validateSync would allow us to create the following document:

const game = new Game({
        title: "Pacman",
        publisher: "Nintendo",
        tags: ["arcade"],
        onSale: true,
        price: 29.99
    });