2016-11-30 59 views
0

驗證用戶我的API接受users作爲JSON發佈。我只想驗證某些字段是否作爲JSON對象的一部分包含在內。使用.pre保存

例如,一個用戶可能是這樣的:

{ 
    "email" : "[email protected]", 
    "username" : "testing", 
    "name" : "Test User" 
} 

,或者它可能沒有一個名稱字段:

{ 
    "email" : "[email protected]", 
    "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屬性,輸出也始終爲「找到名稱」。這是因爲該模型有一個name屬性?

+0

你會記下'UserSchema'嗎?以及「這裏沒有名稱屬性的證據」是什麼意思,什麼是已經記錄的? –

+0

我已經添加了它 – tommyd456

+0

我的意思是,當我在終端中看到用戶對象時,在使用沒有名稱的JSON時沒有'name'屬性。問題是''這個名字''仍然說它存在? – tommyd456

回答

0

你看到在終端的用戶對象,並沒有屬性name因爲貼JSON可能沒有一個名稱字段正如你所說,這樣你就可以做你的邏輯/條件只是當name屬性存在如下:

UserSchema.pre('save', function(next) { 
    if (this.name !== undefined) { 
    if (this.name.length <= 6) { 
     // throw error or whatever 
    } 
    } 
    next(); 
}); 
+0

但是爲什麼'name'屬性總是存在?這是我的問題 – tommyd456

+0

你的問題的答案是YES,因爲模型具有'name'屬性,所以你不需要檢查鍵是否存在,而是檢查值本身,如果傳遞返回字符串,如果沒有返回'undefined',這是有道理的。 –

+0

那麼如何區分用戶的空值和什麼時候它不作爲屬性? 'if(this.name)'將產生假兩個 – tommyd456