i trying create simple leaderboard using mongo. have api build node.js , express.
for have json sorted user points looks this:
[ { "_id": "58e543758222ff220d0af481", "id": 5, "__v": 0, "name": "frank", "points": 653 }, { "_id": "58e543758222ff220d0af479", "id": 1, "__v": 0, "name": "bob", "points": 321 }, { "_id": "58e543758222ff220d0af47b", "id": 2, "__v": 0, "name": "john", "points": 123 }, { "_id": "58e543758222ff220d0af47d", "id": 3, "__v": 0, "name": "bravo", "points": 34 }, { "_id": "58e543758222ff220d0af47f", "id": 4, "__v": 0, "name": "bill", "points": 12 } ]
i have request looks this:
user.find().sort({ points: '-1' }).exec(function(err, users) { if (err) res.send(err); res.json(users); });
and request find specified id.
user.findone({id: req.params.id}, function(err, user) { if (err) res.send(err); res.json(user); });
i send id of user , info him. don't know how find nearest neighbor of specified id. example find user id: 3 how show 1 user before him , 1 after him using points.
thank you
another way query users , filter out using resultset.
user.find().sort({ points: '-1' }).exec(function (err, users) { if (err) // idea add return stop code going further return res.send(err); var nbd = []; (var = 0; < users.length; i++) { // find user given id if (users[i].id == req.params.id) { // add user before him if (i-1 >= 0) { nbd.push(users[i-1]); } // add user nbd.push(users[i]); // add user after him if (i+1 < users.length) { nbd.push(users[i+1]); } // no need search further break; } } res.json(nbd); });
Comments
Post a Comment