Validate object against Mongoose schema without saving as a new document

后端 未结 2 1754
南笙
南笙 2021-02-07 08:03

I\'m trying to validate some data that will be inserted into a new document, but not before a lot of other things need to happen. So I was going to add a function to the static

相关标签:
2条回答
  • 2021-02-07 08:24

    As explained here in the mongoose documents https://mongoosejs.com/docs/validation.html , you can use doc.validate(callback) or doc.validateSync() to check for validation.

    The difference is that you do not have to use await for validateSync() as its name suggests. it returns an error if validation fails, otherwise, it returns undefined. for example:

    const model = new Model({somedata:somedata})
    
    const validatedModel = model.validateSync()
    if(!!validatedModel) throw validatedModel
    
    0 讨论(0)
  • 2021-02-07 08:38

    There is one way to do that through Custom validators. When the validation failed, failed to save document into DB.

    var peopleSchema = new mongoose.Schema({
            name: String,
            age: Number
        });
    var People = mongoose.model('People', peopleSchema);
    
    peopleSchema.path('name').validate(function(n) {
        return !!n && n.length >= 3 && n.length < 25;
    }, 'Invalid Name');
    
    function savePeople() {
        var p = new People({
            name: 'you',
            age: 3
        });
    
        p.save(function(err){
            if (err) {
                 console.log(err);           
             }
            else
                console.log('save people successfully.');
        });
    }
    

    Or another way to do that through validate() with same schema as you defined.

    var p = new People({
        name: 'you',
        age: 3
    });
    
    p.validate(function(err) {
        if (err)
            console.log(err);
        else
            console.log('pass validate');
    });
    
    0 讨论(0)
提交回复
热议问题