Question

I don't understand why my model instance is not overrided:

schema.pre('validate', function(callback: any, done: any){
    if(!this.status){
        var Type = __Dao.getModel('type');
        Type.findOne({name: 'processing', 'category.name': 'languageStatus'}, function(err, role){
            if(err){
                callback(err);
            }else{
                console.log('this: '+JSON.stringify(this))
                this.status = role;
                callback();
            }
        });
    }
    done();
});

Console:

this: {"domain":null,"_events":{},"_maxListeners":10,"emitted":{"complete":[{"code":"a","name":"processing","_id":"52fd475c699127802d298665"}]},"ended":false}

// Other console.log { message: 'Validation failed', name: 'ValidationError', errors: { status: { message: 'Path status is required.', name: 'ValidatorError', path: 'status', type: 'required', value: undefined } } }

I checked and my role is not empty. I think my mistake is on the this.status = role;, this is defined but it looks like I don't override it in the good way.

Any suggestion?

Was it helpful?

Solution

As you mentioned it doesn't look like this.status is the right object. It also looks like you might be using parallel middleware incorrectly. Middleware can be defined as serial Schema.pre('save', function (done) {... or parallel Schema.pre('save', true, function (next, done) {.... Notice the second arg is a boolean indicating that it should be run parallel.

For parallel try the following:

schema.pre('validate', true, function(next, done){
    var self = this; // save a reference to status
    next();  // start working on any other middleware in parallel with this one

    if(!self.status){
        var Type = __Dao.getModel('type');

        return Type.findOne({name: 'processing', 'category.name': 'languageStatus'}, function(err, role){
            if(err){
                done(err);
            }else{
                console.log('status: '+JSON.stringify(status))
                self.status = role;
                done();  // signify this middleware's work is done
            }
        });
    }
    done();
});

If that doesn't work you could try to use serial middleware, to make sure you don't have conflicts in other middleware.

UPDATE: the differences between parallel and serial is only going to matter when you have more than one piece of middleware. Parallel gives you the ability to run all middleware at the same time, and then move on to the actual validation after all are done. Serial will do the first piece of middleware, and wait to start the next piece after the previous one is done, then validating once all are finished.

For an example, image your client service is running on a machine that has to send requests to the database across a network. The time might not be accurate, but for discussion lets assume those requests take about 100ms. Using Serial middleware:

Schema.pre('validate', function (done) {
    Type.findOne({ name: 'steve' }, function (err, doc) { // send request across network
        // ~100ms later we get steve
        // pre validate steve ...
        done(); // Start the next piece of middleware after this is done
    });
});

Schema.pre('validate', function (done) {
    Type.findOne({ name: 'Jim' }, function (err, doc) { // send request across network
        // ~100ms later we get Jim
        // pre validate Jim ...
        done(); // Start the next piece of middleware after this is done
    });
});

Total time == ~ 200+ms

If you run them parallel the requests to the database can go at nearly the same time.

Schema.pre('validate', true, function (next, done) {
    next(); // start the next piece of middleware before sending request
    Type.findOne({ ... }, function (err, doc) { // send request across network
        // ~100ms later we get the doc
        // do stuff ...
        done();
    });
});

Schema.pre('validate', true, function (next, done) {
    next(); // start the next piece of middleware before sending request
    Type.findOne({ ... }, function (err, doc) { // send request across network
        // ~100ms later we get the doc
        // do stuff ...
        done();
    });
});

Total time ~ 100+ms

OTHER TIPS

Try saving the model and logging any errors from there. So after the line: this.status = role; do this:

this.save(function(err, info) {
    if(err) {
        console.log('Error saving the model:', err);
        return;
    }
    console.log('Saved: ', info);
});

It might give you more info on has failed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top