2017-02-21 50 views
0

我得到的数据是这样的:如何访问猫鼬数据:的NodeJS

这是代码:

User.find({ Username: user }, function(err, found_user) { 

        console.log('user data'+ found_user); 

        if(found_user.length > 0){ 

         console.log('inside found user'); 
         var recordings = found_user.recordings; 
         console.log(recordings) 
         for (var singleRecords in recordings){ 
          console.log("Single record :"+singleRecords); 
          if(!singleRecords.isPlayed){ 
           console.log(singleRecords.playingUrl); 
           twiml.play(singleRecords.playingUrl); 
           found_user.recordings[singleRecords].isPlayed = true; 
           found_user.save(function (err) { 
            if(err) 
             throw err 
           }); 


          } 
         } 
        } 

这是发现用户的价值:在

user data { Username: 'B', 
    __v: 2, 
    _id: 58ac15e4b4e1232f6f118ba3, 
    recordings: 
     [ { isPlayed: false, 
      playingUrl: 'http://localhost:8000/public/toplay/playing_file_1487672817599.mp3' }, 
     { isPlayed: false, 
       playingUrl: 'http://localhost:8000/public/toplay/playing_file_1487672827411.mp3' } ] 
     } 
inside found user 

变量found_user。但它并没有给我任何数据。像found_user.Username给出未定义的值。 我想将该录音数组存储在变量中。任何想法如何做到这一点?

+1

请告诉我们您正在尝试的代码? –

+1

第一个日志found_user使用'console.log(found_user);'并向我们显示输出 – nivas

+0

@nivas请参阅更新的问题 –

回答

1

find()返回在回调因此线,因为它是期待一个文档不是数组

var recordings = found_user.recordings; 

将不起作用与条件匹配的文档的阵列。

你可以使用findOne()方法返回一个文档:

User.findOne({ Username: user }.exec(function(err, found_user) {  
    console.log('user data'+ found_user); 
    if (found_user) { 
     console.log('inside found user'); 
     var recordings = found_user.recordings; 
     console.log(recordings); 
    } 
});