Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Mongoose Validation Race Condition?

Mongoose Validation Race Condition?

Problem

I have a model called Application:

var ApplicationSchema = new mongoose.Schema({
name       : {type: String, validate: [uniqueName, 'Unique Name']},
dateCreated: Date,
containers : [ContainerSchema]
});
mongoose.model('Application', ApplicationSchema);
var Application = database.model('Application');

It calls a validation function called uniqueName when it saves:

function uniqueName(name)
{
console.log('In Unique Name function');
Application.find({}, function(error, documents) {
    for(var i = 0; i 

Later on in the code I put some data in the model and save it:

newApplication.name = request.body.name;
newApplication.save(function(error) {
    console.log('Callback for save');
    if(error) {
        console.log('error if statement');
        response.statusCode = 409;
        response.end();
    }
    console.log('Done with callback');
});
response.statusCode = 201;
response.end();

When I test this with a name that is not unique, I get a 201 response and the following output from my terminal:

In Unique Name function
Callback for save
Done with callback
About to return false

Am I doing something wrong, or is this really a race condition in Mongoose?

Problem courtesy of: amandawulf

Solution

When your validator is asynchronous (as it is here) it needs to accept a second parameter which is a callback that you must call with true or false, depending on whether that validation passed. So:

function uniqueName(name, callback)
{
    Application.find({}, function(error, documents) {
        for(var i = 0; i 

However, this is not very efficient; you should either:

Filter your find instead of getting all docs and manually searching them. e.g.

Application.find({name: name} ...

OR even better:

Create a unique index on name and let mongo ensure uniqueness for you. e.g.

var ApplicationSchema = new mongoose.Schema({
    name: {type: String, unique: true}, 
    ...
Solution courtesy of: JohnnyHK

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Mongoose Validation Race Condition?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×