Miguel Lorenzo Miguel Lorenzo - 2 years ago 135
Node.js Question

How to check if that data already exist in the database during update (Mongoose And Express)

Hey guys I have a question, how to do validations before saving the edited data in mongoose

for Example, if sample.name already exist in the database, the user will receive a some sort of error, something like that, here's my code below

//Post: /sample/edit
app.post(uri + '/edit', function (req, res, next) {
Sample.findById(req.param('sid'), function (err, sample) {

if (err) {
return next(new Error(err));

if (!sample) {
return next(new Error('Invalid reference to sample information'));

// basic info
sample.name = req.body.supplier.name;
sample.tin = req.body.supplier.tin;

// contact info
sample.contact.email = req.body.supplier.contact.email;
sample.contact.mobile = req.body.supplier.contact.mobile;
sample.contact.landline = req.body.supplier.contact.landline;
sample.contact.fax = req.body.supplier.contact.fax;

// address info
sample.address.street = req.body.supplier.address.street;
sample.address.city = req.body.supplier.address.city;
sample.address.state = req.body.supplier.address.state;
sample.address.country = req.body.supplier.address.country;
sample.address.zip = req.body.supplier.address.zip;

sample.save(function (err) {
if (err) {
return next(new Error(err));

res.redirect(uri + '/view/' + sample._id);


Answer Source

Typically you could use mongoose validation but since you need an async result (db query for existing names) and validators don't support promises (from what I can tell), you will need to create your own function and pass a callback. Here is an example:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;


var UserSchema = new Schema({
    name: {type:String}

var UserModel = mongoose.model('UserModel',UserSchema);

function updateUser(user,cb){
    UserModel.find({name : user.name}, function (err, docs) {
        if (docs.length){
            cb('Name exists already',null);

   if (!err && existingUser){
       existingUser.name = 'Kevin';
           if (err2 || !user){
               console.log('error updated user: ',err2);
               console.log('user updated: ',user);


UPDATE: A better way

The pre hook seems to be a more natural place to stop the save:

UserSchema.pre('save', function (next) {
    var self = this;
    UserModel.find({name : self.name}, function (err, docs) {
        if (!docs.length){
            console.log('user exists: ',self.name);
            next(new Error("User exists!"));
}) ;

UPDATE 2: Async custom validators

It looks like mongoose supports async custom validators now so that would probably be the natural solution:

    var userSchema = new Schema({
      name: {
        type: String,
        validate: {
          validator: function(v, cb) {
            //test for user existence
          message: 'User already exists!'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download