简体   繁体   中英

Get Next and Previous MongoDB with Javascript

I have an Express app with MongoDB and Mongoose. The app displays image galleries for different projects which are all held in the DB. I'd like each image gallery to link to the previous and next projects held in the DB, so I'm trying to get the IDs of those projects and pass them into the EJS template:

app.get('/projects/:_id', function(req, res){
nextProject = Project.findById({_id: {$gt: req.params._id}}).sort({_id: 1 }).limit(1)
console.log('Next Project');
console.log(nextProject);

But this returns an error:

{ CastError: Cast to ObjectId failed for value "{ _id: { '$gt': '57d09754943f2403738edb04' } }" at path "_id"

How should I get the previous and next entries in the database? Actually it doesn't really matter if they are the previous and next entries in the DB, just as long as they're different from the one currently being displayed.

In case it's useful, here's the Project schema:

var mongoose = require('mongoose');

var projectSchema = new mongoose.Schema({
  title: String,
  description: String,
  images: Array
});

module.exports = mongoose.model('Project', projectSchema);

Thank you!

You just need to change findById to find .

findById accepts the _id of the document you're looking to find, not a query object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM