2

I'm having issues placing the last added item in a list of object/items appear at the top. Basically its like a job board and i want the latest jobs appear at the top and not the bottom. I've tried using Post.find({}).sort({ date: -1}).exec(function (err, posts) {... });but it doesn't seem to be working or maybe i'm not implementing it correctly, i'm still quite new to this.

// Example code, but similar to actual code
 
//models config
let jobSchema = new mongoose.Schema({
 title: String,
 category: String,
 description: String,
 type: String,
 url: String,
 email: String,
 apply: String,
 location: String,
 company: String,
 path: String,
 created: {type: Date, default: Date.now}
})

let Job = mongoose.model('job', jobSchema);
// {type: String, default: "placeholdeimage.jpg"}

//routes config

var storage = multer.diskStorage({
 destination: function (req, file, cb) {
   cb(null, './public/uploads/');
 },

 filename: function (req, file, cb) {
     var originalname = file.originalname;
     var extension = originalname.split(".");
     filename = Date.now() + '.' + extension[extension.length-1];
     cb(null, filename);
 }
});


app.get('/', (req, res) =>{
 res.redirect('/jobs')
})

app.get('/jobs',  (req, res) =>{
 Job.find({}).sort({ date: -1}).find(function(err, jobs){
  if(err){
   console.log('error')
  }
  
  return res.render('index', {jobs: jobs})

 })

})

//add form route
app.get('/jobs/add', (req, res) => {
 res.render('add')
})

app.post('/jobs', multer({storage: storage, dest: 
'./public/uploads/'}).single('file'), (req, res) => {
 
 req.body.description = req.sanitize(req.body.description);
 
 Job.create( (err, addJob) =>{
  
  if(req.file){
            let fullPath = "uploads/"+req.file.filename;
            let document = {
               title: req.body.title,
    category: req.body.category,
    description: req.body.description,
    type: req.body.type,
    url: req.body.url,
    email: req.body.email,
    apply: req.body.apply,
    location: req.body.location,
    company: req.body.company,
               path: fullPath
            };

         let job = new Job(document); 
            job.save()
  }else{
   console.log('file not uploaded')
   logo = 'noimage.jpg'
  }
  
  //redirect to index page
  return res.redirect('/jobs')
 })
})

app.get('/jobs/:id', (req, res) => {
 Job.findById(req.params.id, (err, jobDetails) => {
  if(err){
   res.redirect('/jobs')
  }else{
   res.render('details', {job: jobDetails});
  }
 })
})


app.listen(port, process.env.PORT, process.env.IP, ()=> console.log(`Server 
is running on ${port}`))
<!--writen in EJS-->
<div class="container">

  <% for (const job of jobs) { %>
    <div class="row">
      <div class="column logo" style="width:10%;">
        <img src='<%= job.path %>'>
      </div>
      <div class="column title">
        <h2>
          <%=job.title%>
        </h2>
        <p>
          <%=job.company%>
        </p>
      </div>
      <div class="column type">
        <h2>
          <%=job.type%>
        </h2>
      </div>
      <div class="column location">
        <h2>
          <%=job.location%>
        </h2>
      </div>
      <div class="column">
        <h2><a href="/jobs/<%= job._id %>"><button>Apply</button></a></h2>
      </div>
    </div>
    <hr>
  <% } %>

</div>
seyi
  • 121
  • 1
  • 1
  • 11

1 Answers1

3

Sorting in MongoDB is done like so:

db.Post.find({ MATCHING CRITERIA }).sort({ date: 1 })

where 1 is ascending and -1 is descending.

Akrion
  • 18,117
  • 1
  • 34
  • 54
Ishan Garg
  • 571
  • 5
  • 13