node.js - 如何在更新期间检查该数据是否已存在于数据库中(Mongoose And Express)

标签 node.js validation express mongoose

如何在mongoose中保存编辑后的数据之前进行验证?

例如,如果 sample.name 已经存在于数据库中,用户会收到某种错误,类似这样,下面是我的代码

//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);
    });

  });
});

最佳答案

通常您可以使用 mongoose validation但是由于您需要异步结果(数据库查询现有名称)并且验证器不支持 promise (据我所知),因此您需要创建自己的函数并传递回调。这是一个例子:

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

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

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);
        }else{
            user.save(function(err){
                cb(err,user);
            });
        }
    });
}

UserModel.findById(req.param('sid'),function(err,existingUser){
   if (!err && existingUser){
       existingUser.name = 'Kevin';
       updateUser(existingUser,function(err2,user){
           if (err2 || !user){
               console.log('error updated user: ',err2);
           }else{
               console.log('user updated: ',user);
           }

       });
   } 
});

更新:更好的方法

pre 钩子(Hook)似乎是一个更自然的停止保存的地方:

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

更新 2:异步自定义验证器

看起来 mongoose 现在支持异步自定义验证器,所以这可能是自然的解决方案:

    var userSchema = new Schema({
      name: {
        type: String,
        validate: {
          validator: function(v, cb) {
            User.find({name: v}, function(err,docs){
               cb(docs.length == 0);
            });
          },
          message: 'User already exists!'
        }
      }
    });

关于node.js - 如何在更新期间检查该数据是否已存在于数据库中(Mongoose And Express),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16882938/

相关文章:

windows - 专为 Unix 设计的 Node.js 模块?

javascript - 如何在用户键入时更新 JavaScript 表单验证

c# - 使用 ErrorProvider 组件在 WinForms 中进行数据验证

html - 谷歌风格的 Bootstrap 主题会抛出大量 CSS 验证错误。使用样式表安全吗?

node.js - 使用 HBS strip (消耗?)Handlebars 客户端模板进行快速 View 渲染

node.js - Mongoose 架构错误 : "Cast to string failed for value" when pushing object to empty array

javascript - 无法进入异步(同步)函数/空结果的回调

javascript - socket.io 是如何工作的?

node.js - Heroku 的 Nodejs 端口错误

node.js - 如何在 NodeJS/ExpressJS 中连接两个数组