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

后端 未结 8 1931
灰色年华
灰色年华 2020-12-05 00:28

How to do validations before saving the edited data in mongoose?

For example, if sample.name already exists in the database, the user will receive a som

8条回答
  •  忘掉有多难
    2020-12-05 00:50

    Here is another way to accomplish this in less code.

    UPDATE 3: Asynchronous model class statics

    Similar to option 2, this allows you to create a function directly linked to the schema, but called from the same file using the model.

    model.js

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

    Call from file

    var User = require('./path/to/model');
    
    User.updateUser(user.name, function(err, user) {
      if(err) {
        var error = new Error('Already exists!');
        error.status = 401;
        return next(error);
      }
    });
    

提交回复
热议问题