使用.pre save验证用户

时间:2016-11-30 13:01:42

标签: javascript express mongoose

我的API接受users POST为JSON。我想仅在某些字段作为JSON对象的一部分包含时才验证它们。

例如,用户可能如下所示:

{
  "email" : "test@test.com",
  "username" : "testing",
  "name" : "Test User"
}

或者它可能没有名称字段:

{
  "email" : "test@test.com",
  "username" : "testing"
}

我想确保name至少包含6个字符(如果它是一个包含的字段)。

我正在尝试使用.pre将验证过程构建到我的模型中,但事情并不像我期望的那样。

var UserSchema = new Schema({
  id                      : String,
  name                    : String,
  email                   : String,
  username                : String
},{ timestamps: { createdAt: 'created_at',updatedAt: 'updated_at' } });

UserSchema.pre('save', function(next) {
  console.log(this); //no evidence of name property here

  if("name" in this){
    console.log("Name found"); //this is always the output
  } else {
    console.log("Name not found");
  }
  next();
});

以上代码用于测试。使用上面的任何一个JSON对象,输出始终为“Name found”,即使输出到控制台时对象没有name属性。这是因为该模型具有name属性吗?

1 个答案:

答案 0 :(得分:0)

您在终端中看到了用户对象,并且name没有属性,因为发布的json可能没有您提到的名称字段,因此您可以在{{1}时执行逻辑/条件属性存在如下:

name