Brave Shine
Brave Shine

Reputation: 65

TypeError: Cannot read property 'name' of undefined

Post.find({}, function (error, data){
            var proj = [];      
            for (var i = 0; i < data.length; i++) {
                    proj.push({
                        image: "none",
                        name: "none",
                        pPic: "none",
                    profession: "none"
                });
            }
             // reverse post order           
            function aSyncLoop(i, callback) {
                if (i>=0){
                    proj[data.length-i-1].image = data[i].imagelink[0];      
                    User.find({'_id' :  data[i].author}, function(error, userdata){
                        proj[data.length-i-1].name = userdata.local.name+ " " + userdata.local.surname; 
                    });
                    aSyncLoop(i-1, callback);
                } else { callback(); }
            }
        aSyncLoop(data.length-1, function() {
            console.log('callback');
        });

The error happens here:

proj[data.length-i-1 ].name = userdata.local.name+ " " + username.local.surname;

I guess the problem relies on the assignment being inside a Find query but i wouldn't know how to fix it.

Upvotes: 2

Views: 2012

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50406

The "userdata" returned from .find() is an "array" and not a singular object.

The easy fix is to use .findOne() when you only expect a single result, such as fetching by the primary key. Better yet, .findById():

User.findById(data[i].author, function(error, userdata){
  console.log(userdata);
  proj[data.length-i-1].name = userdata.local.name+ " " + userdata.local.surname; 
});

Upvotes: 1

Related Questions