Barry Bonds
Barry Bonds

Reputation: 118

node: res.send-ing an array not working

My User model has a field of type Array with values like this

"courseId" : [
   "5ac1fe64cfdda22c9c27f264",
   "5ac207d5794f2910a04cc9fa",
   "5ac207d5794f2910a04cc9fa"
]

My routes are configured in this way:

router.get('/:userid/vendor-dashboard', function (req, res) {
    var courseID = [];
    User.findById(req.params.userid, function (err, doc) {
        if (err) {
            res.send(err);
        } else {
            for (var i = 0; i < doc.courseId.length; i++) {
                Course.findById(doc.courseId[i], function (err, course) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log(course.title);
                        courseID.push(course.title);
                    }
                })
            }
            res.send(JSON.stringify(courseID));
        }
    })
})

First I'm finding a user and when user is found, He should find all the courses in the array and display their title.

Now, I'm able to get the title in console, but when I try to send it through res.send, it shows an empty array.

What am I doing wrong?

Upvotes: 0

Views: 143

Answers (1)

AlexScr
AlexScr

Reputation: 452

The main problem is that you are sending the response before getting the response from Course model.

The correct way using callback will be:

router.get('/:userid/vendor-dashboard', function(req, res) {
var courseID = [];
User.findById(req.params.userid, function(err, doc) {
    if (err) {
        return res.send(err);
    }

    var resolved = 0;
    for (var i = 0; i < doc.courseId.length; i++) {
        Course.findById(doc.courseId[i], function(err, course) {
            if (err) {
                return console.log(err);
            }

            courseID.push(course.title);

            if (++resolved === doc.courseId.length) {
                res.send(JSON.stringify(courseID));
            }
        })
    }
})
})

Upvotes: 1

Related Questions