Sharad Chauhan
Sharad Chauhan

Reputation: 4891

How to access mongoose data : Nodejs

I am getting data like this:

This is the code :

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
                                });


                            }
                        }
                    }

And this is the value of found User :

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

in variable found_user. But it is not giving me any data inside it. Like found_user.Username gives undefined value. I want to store that recordings array inside a variable. Any idea how to do it ?

Upvotes: 0

Views: 100

Answers (1)

chridam
chridam

Reputation: 103435

find() returns an array of docs that match the criteria in the callback hence the line

var recordings = found_user.recordings;

will not work as it's expecting a Document not an array.

You could use findOne() method which returns a document as:

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);
    }
});

Upvotes: 2

Related Questions