Friday, 21 April 2017

Why is my code skipping over my sort function after my map function?

I am trying to assign a score to each user submitted post as I a retrieve it from my mongo db. I go through the whole process and successfully add a 'score' property in my new array of posts objects. Now, I want to sort the posts based on that score. I am trying to use a simple compare function but it seems my code isnt even hitting this function.

I am not getting errors or anything printed to the console. All I get is my posts object in an array with a score property assigned.

Why is my code skipping over this sort function?

Thank you in advance.

postDB.connect
.then(db => db.collection("posts").find().forEach(function(posts) {


    var postsArr = [];
    postsArr.push(posts);


    function generateScore(postWithoutScore) {


        var timeSince = (((Date.now()/1000) - postWithoutScore.e) * 0.000277778);

        var hh = ((postWithoutScore.upvote - 1)/Math.pow(timeSince + 2, 1.8)).toFixed(2);

        return hh;
    }

    var postsWithScore = postsArr.map(function(post) {
        // console.log(post);
        return Object.assign({}, post, {
            score: generateScore(post)
        })
    });


    postsWithScore.sort(function (a, b){

        console.log(b);
        console.log(a);

        return b[i].score - a[i].score;

    });

    console.log(postsWithScore);


    })
    .then(posts => {
       console.log(posts);
       res.render("projects", {
          posts: posts
       })
     })
     .catch(next))
     });



via Andrew Little