2016-01-20 63 views
0

我一直在試圖擺脫我創建用於存儲用戶數據庫貓鼬密碼屬性。我能得到的用戶名就好了,但是當我嘗試使用它來獲取密碼:嘗試接收來自貓鼬數據庫返回值未定義?

User.find({ 'credentials.username': gusername }, function(err, user) { 
if (err) throw err; 
console.log(user); 
console.log(user.credentials.password); 
}); 

它記錄這個控制檯:

Connected to the DB using Mongo! 
GET /login 200 66.097 ms - 1931 
GET /stylesheets/style.css 304 2.212 ms - - 
drew 
[ { credentials: { password: 'tueresputa99', username: 'drew' }, 
__v: 0, 
_id: 569e5e99e7810411003c4c25 } ] 
/home/ubuntu/workspace/routes/index.js:127 
console.log(user.credentials.password); 
          ^

TypeError: Cannot read property 'password' of undefined 
at Query.<anonymous> (/home/ubuntu/workspace/routes/index.js:127:33) 
at /home/ubuntu/workspace/node_modules/mongoose/node_modules/kareem/index.js:177 :19 
at /home/ubuntu/workspace/node_modules/mongoose/node_modules/kareem/index.js:109:16 
at doNTCallback0 (node.js:417:9) 
at process._tickCallback (node.js:346:13) 
[nodemon] app crashed - waiting for file changes before starting... 

因此,大家可以看到,它成功登錄「用戶」,你可以看到用戶名和密碼就在那裏,不過不失,我不能user.credentials.password

任何幫助表示讚賞得到密碼!這非常令人沮喪:/

回答

2

您的user裏面的callback函數是一個數組而不是一個對象。通知用戶對象之前的JSON數組方括號 -> [ <- { credentials:

如果您的目的是要找到恰好一個用戶,則應使用User.findOne函數。

看到這個:http://mongoosejs.com/docs/api.html#query_Query-findOne

+0

所以,我將不得不使用'User.findOne({ 'credentials.username':gusername},功能(ERR,用戶){',然後我可以用'用戶。 credentials.password'? – dec0mpiled

+0

天啊,它的工作。我不知道怎麼感謝你纔好! – dec0mpiled

+0

@ dec0mpiled歡迎您,很高興我能幫助 –