2015-08-24 51 views
1

我使用郵遞員發佈到我的後端,以獲得基於他的用戶名和密碼的用戶。貓鼬(mongodb)奇怪的行爲時,查詢沒有參數

每當用戶名不存在作爲表單中的字段時,用戶仍然返回(我目前只有一個用戶,他被返回);

但是,如果我添加username字段,它將返回null,除非它是正確的用戶名,即使它是空的。

這是代碼:

User.findOne({ 
    username: req.body.username 
    }, function(err, user) { 
    if(err) throw err; 

    // prints null if username field is present and incorrect even if its empty 
    // prints a user as json if the username field is not present 
    console.log(user); 
    if(!user) { 
     res.json({ success: false, message: 'Authentication failed. User not found.' }); 
    } 

我仍然檢查密碼,這樣就不會有人張貼未經用戶名字段工作,但它是非常奇怪的,防止右的錯誤消息顯示。爲什麼會發生?

回答

1

您必須先檢查參數是否存在,否則req.body.username將等於undefined,這將導致空查詢。

findOne使用空查詢將獲取找到的第一個文檔,因爲您可以使用空查詢獲取所有帶有find的文檔。

一個空字符串不會產生空的查詢,這就是爲什麼你得到null(你沒有任何用戶作爲''作爲用戶名)。

TLDR:在構建查詢之前檢查每個參數的存在,並在構建REST API時返回一些409 MissingParameterError