I am creating a photography website and eventually I would like to add the functionality for the user to see the next photo in the database. I am new to web development and therefore want to proceed step by step, so for now it would be enough if the id of the next photo would be displayed in the console. This is the code I use right now:
var getPhoto = require("../public/modules/getPhoto")
router.get("/:id/next", function(req, res){
getPhoto.next();
res.redirect("/");
})
and
var Photo = require("../../models/photo");
var exports = module.exports = {};
exports.next = function(callback){
console.log(Photo.find({}).sort({_id: 1 }).limit(1)._id);
}
However, this only returns undefined
.
I read here that I need to use callbacks, but I don't know how to implement it, even with the code given in the example in the link.
How can I print the id of the next photo to console?
Edit My code now looks like this:
// NEXT PHOTO - shows next photo
router.get("/:id/next", function(req, res){
Photo.find({}).sort({ _id: 1 }).limit(1).then(function(docs){
console.log(docs[0]._id)
res.redirect("/photos/" + docs[0]._id)
})
})
// PREVIOUS PHOTO - shows previous photo
router.get("/:id/previous", function(req, res){
Photo.find({}).sort({ _id: -1 }).limit(1).then(function(docs){
console.log(docs[0]._id)
res.redirect("/photos/" + docs[0]._id)
})
})
However, this only gives me the first or last item in the database. According to this link I have to substitute { _id: -1 }
for {_id: {$gt: curId}}
. I am not using jQuery, so how can I rewrite this?