24

I'm trying to create a User model, that has an unique username. Here's the code for it:

var mongoose = require("mongoose");

var Schema = mongoose.Schema;

var UserSchema = new Schema({
    username: String,
    password: String,
});

UserSchema.virtual("password_confirmation").get(function() {
    return this.pw_conf;
}).set(function(value) {
    this.pw_conf = value;
});

UserSchema.path("username").required(true);
UserSchema.path("password").required(true);

UserSchema.pre("save",function(next, done) {
    var self = this;
    mongoose.models["User"].findOne({username : self.username},function(err, user) {
        if(user) {
            self.invalidate("user","username must be unique");
        }
        done();
    });
    next();
});

UserSchema.pre("save",function(next) {
    if(this.pw_conf !== this.password) {
        next(new Error("Must specify the password confirmation"));
    }
    else {
        next();
    }
});

module.exports = mongoose.model("User",UserSchema);

I was also testing to see if the uniqueness works:

var User = require("./users"),
  mongoose = require("mongoose");
var u = new User();

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

u.username = "me";
u.password = "password";
u.password_confirmation = "password";
u.save(function(err) {
    if(err) {
        console.log(err);
    }
    mongoose.disconnect();
});

Problem is, it doesn't. Each time I run the code, I get a new object created. I am aware that there are probably other ways of ensuring uniqueness, but I'd like to do it in this way. Shouldn't I be calling done after I handle the result of the findOne method? Am I calling next wrong?

1
  • as of 2022, all you need to do is putting "unique:true" into the field's setting, mongoose will take care of the rest for you Feb 21, 2022 at 18:20

4 Answers 4

33

http://mongoosejs.com/docs/api.html#schematype_SchemaType-unique is the way to go. It uses actual MongoDb indexes to make sure that your field is unique. No need for .pre middleware.

Enjoy!

3
29
+50

To use parallel middleware (with next and done parameters), you need to pass true as the second parameter.

Beyond that, there are two possibilities:

Your self.invalidate call should be referencing "username" instead of "user". If that doesn't fix it, you can fail things explicitly by passing an Error object to done if you want to abort the save operation:

UserSchema.pre("save", true, function(next, done) {
    var self = this;
    mongoose.models["User"].findOne({username: self.username}, function(err, user) {
        if(err) {
            done(err);
        } else if(user) {
            self.invalidate("username", "username must be unique");
            done(new Error("username must be unique"));
        } else {
            done();
        }
    });
    next();
});
3
  • 1
    It worked, but the error format isn't the same so if you're building an API and counting on the error object format you're probably going to have issues with that approach. I've tested the npmjs.org/package/mongoose-unique-validator and it worked like a charm for me. The error object is pretty much the same. Jun 23, 2014 at 13:59
  • 1
    for me, this didn't work, I had to change the signature of the function to have only one argument (next) and then calling next with error or next without parameters accordingly
    – Matus
    Feb 28, 2015 at 21:19
  • @Matus There are two types of pre middleware: parallel (with the next, and done params), and serial (with just the next).
    – JohnnyHK
    Feb 28, 2015 at 21:58
5

There's a really good plugin for mongoose that's really easy to install and use. The documentation is excellent and it worked for me first time.

But there is an issue with re-saving.

https://npmjs.org/package/mongoose-unique-validator

1
  • Usually against bringing more modules into projects, but I also think that this is a must if you're going to do a lot of validation and it pretty much doesn't require any refactor to integrate
    – kuzyn
    Jun 1, 2016 at 16:36
3

Have you considered using an asynchronous validator to catch the error?

UserSchema.path('username').validate(function (value, done) {
  User.count({ username: value }, function (error, count) {
    // Return false if an error is thrown or count > 0
    done(!(error || count));
  });
}, 'unique'); 
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.