question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Validation not working on undefined model properties

See original GitHub issue

Hey,

Not sure if this is working as intended or not, but I noticed that if I instantiate a model then immediately save it, the validation rules on the individual properties are not run.

I created a small script below to demonstrate what I mean. If you run this with mocha, the first test on the user model will fail because err is null after the save, when I was expecting the validation to fail because user.email == undefined.

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    should = require('should'),
    UserSchema,
    User;

mongoose.connect('mongodb://localhost/test');

function validatePresenceOf (value) {
    if(typeof value === 'string' || typeof value === 'number') {
        value = value.toString().trim();
    }
    return !!(value && value.length);
}

UserSchema = new Schema({
    email : {type: String, 
        validate: [validatePresenceOf, "email required"],
        index: {unique: true}
    },
    hashed_password : String,
    salt : String
});

User = mongoose.model('User', UserSchema);

describe('validatePresenceOf', function () {
    it("should return false for undefined", function () {
        validatePresenceOf(undefined).should.be.false;
    });

    it("should return false for empty string", function () {
        validatePresenceOf('').should.be.false;
    })
})

describe("User model", function () {
    describe("validation", function () {
        afterEach(function () {
            User.find().remove();
        });

        it(" does not validate if user.email is not set first", function (done) {
            var user = new User();

            // expecting validation to fail because validatePresenceOf returns
            // false, but err is null
            user.save(function (err) {
                should.exist(err);
                err.toString().should.equal('ValidationError: Validator ' + 
                    '"email required" failed for path email');
                done();
            });
        });

        it("is fine if I set user.email", function (done) {
            var user = new User();
            user.email = '';

            // validation works fine if I set user.email before saving
            user.save(function (err) {
                should.exist(err);
                err.toString().should.equal('ValidationError: Validator ' + 
                    '"email required" failed for path email');
                done();
            });
        });
    });
});

Issue Analytics

  • State:closed
  • Created 11 years ago
  • Comments:14 (1 by maintainers)

github_iconTop GitHub Comments

6reactions
jonstorercommented, Jun 9, 2014

There should not need to be a trick to make it work.

2reactions
successivesoftwarecommented, May 13, 2015

use default: null worked for me.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unable to get property 'validate' of undefined or null reference
I have attached a validator to the container and got a reference by doing below: var validator = $("#sectionContainer").
Read more >
undefined - JavaScript - MDN Web Docs - Mozilla
The global undefined property represents the primitive value undefined. It is one of JavaScript's primitive types.
Read more >
TypeError: Cannot read property 'validate' of undefined? - React
“Cannot read property 'validate' of undefined”? Anyone can help in finding the error. ... Is there any more to that error? For example...
Read more >
Mongoose v6.8.2: Validation
Validators are not run on undefined values. The only exception is the required validator. Validation is asynchronously recursive; when you call Model#save, ...
Read more >
Model validation in ASP.NET Core MVC | Microsoft Learn
Web API controllers don't have to check ModelState.IsValid if they have the [ApiController] attribute. In that case, an automatic HTTP 400 ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found