2013-04-04 25 views
0

我正在使用Express,Mongoose和PassportJS製作基本身份驗證系統。 我想要做的是檢查數據庫,如果輸入的用戶名和密碼已經存在於數據庫中。下面是我下面的示例代碼:如何在保存在Mongoose之前檢查數據庫中是否存在嵌入式文檔

//Post: /signup 
app.post('/signup', function (req, res) { 
    var username = req.body.person.user.username; 
    var password = req.body.person.user.password; 

    Person.user.find({'username': username}, function (err, user) { 
    if (err) { 
     console.log(err.name); 
    } else { 
     console.log('User Found'); 
    } 
    }); 
}); 

問題是,它返回此類型的錯誤:

TypeError: Cannot call method 'find' of undefined 

可能有人請幫助我。

+0

錯誤說Person.user是不確定的...首先初始化一個對象,比它 – ogres 2013-04-04 11:02:51

回答

3

正如robertklep指出的那樣,您不能正確檢查用戶的存在。另外,由於用戶名最可能是唯一的,因此可以使用findOne(findOne()返回單個對象,而find()也可以返回單個對象,但會將其包裝在數組中)。

Person.findOne({'username': username}, function (err, user) { 
    if (err) { 
    console.log(err.name); 
    return; 
    } 
    if (!user) 
    console.log('User not Found'); 
    return; 
    } 
    console.log('User found'); 

}); 
+0

嗨,謝謝你的解決方案 – 2013-04-05 05:32:56

0

我認爲你正在尋找這樣的:

Person.find({ 'user.username' : username }, ...) 

FWIW,如果回調不與錯誤稱爲,這並不意味着用戶被發現,它只是意味着沒有執行查詢時出錯。但是user仍然可以爲空,表示查詢沒有任何匹配結果。

+0

調用方法我試過這種方法,但問題是,它返回以下錯誤:第一個對象{:類型錯誤「米格爾」, 最後: '洛倫佐', _id:515e3c2d99ebf01706000020, __v:0, 用戶:{用戶名: 'MIGO123',密碼: '123',使:真}, 兄弟姐妹:[], 外水: ], educations:[], mother:{affiliate:false}, father:{affiliate:false}, address:{}, contact:{}}沒有方法'find' – 2013-04-05 03:04:42

+0

'Person'是什麼?看起來你會用結果覆蓋你的模型類。你可以將你的模式添加到你的問題中嗎? – robertklep 2013-04-05 05:29:12

相關問題