SalokinSwift
SalokinSwift

Reputation: 159

Sorting up updatedAt mongoDB

So on my webpage www.groupwrites.com I am showing an Index of stories in the "Read" page. These stories currently show in the order of which they were created (i.e the newest ones on bottom). I am trying to figure out how to display them with the most recently created/updated one first. I am using mongoDB, node JS on cloud9. I have been trying to research and know that I should use updatedAt but I am not sure how to plug everything in. I am not sure how to update the timestamp for updatedAt in the put routes.

This is my code for the index:

// INDEX - show all stories

router.get("/browse", function(req, res, next){
    // Get all stories from DB
    Story.find({}, function(err, allStories){
       if (err) { 
           return next(err); 
        } else {
            // if user is logged in then render stories and any alerts
            if(req.user) {
                User.findById(req.user._id).populate({
                    path: 'alerts',
                    model: 'Alert',
                    match: { 'isRead': { $eq: false }}
                }).exec(function(err, user) {
                    if(err) {
                        return next(err);
                    }
                    res.render("stories/index", {stories:allStories, alerts: user.alerts.length, page: 'browse'});
                });
            } else {
                res.render("stories/index", {stories:allStories})
            }
        }
    })
})

// CREATE - add new story to DB

router.post("/browse", middleware.isLoggedIn, function(req, res, next){
    // get data from form and add to stories array
    var title = req.body.title
    var image = req.body.image
    var desc = req.body.description
    var category = req.body.category
    var author = {
        id: req.user._id,
        username: req.user.username
    }
    var newStory = {title: title, image: image, description: desc, author: author, category: category}
    // Create a new story and save to database
    Story.create(newStory, function(err, newlyCreated){
        if (err) { 
            return next(err);
        } else {
            // redirect back to stories page
            req.flash("success", "Successfully published story!")
            res.redirect("/browse")
        }
    })
})

This is the code for the content of the stories, (i.e when adding a chapter to the story):

// New Content

router.get("/stories/:id/content/new", middleware.isLoggedIn, function(req, res, next){
    // Find story by id
    Story.findById(req.params.id, function(err, story){
        if (err) { 
            return next(err);
        } else {
            res.render("content/new", {story: story}) 
        }
    })
})

// Create Content
router.post("/stories/:id/content", middleware.isLoggedIn, function(req, res, next){
    // Look up story using ID
    Story.findById(req.params.id).populate({path: 'subscribors', model: 'User'}).exec(function(err, story){
        if (err) { 
            return next(err);
        } else {
            Content.create(req.body.content, function(err, content){
                if (err) { 
                    return next(err);
                } else {
                    if(story.subscribors.length) {
                        var count = 0;
                        story.subscribors.forEach(function(subscribor) {
                            // create alert for each subscribor and add to subscribor's alerts
                            Alert.create({follower: story.author.id, followed: subscribor, story: story, isUpdated: true}, function(err, newAlert) {
                                if(err) {
                                    return next(err);
                                }
                                // console.log(newAlert);
                                subscribor.alerts.push(newAlert);
                                subscribor.save();
                                count+=1;
                                if(count === story.subscribors.length) {
                                    // Add username and ID to content
                                    content.author.id = req.user._id;
                                    content.author.username = req.user.username;
                                    // Save content
                                    content.save();
                                    story.content.push(content);
                                    story.save();

                                    req.flash("success", "Successfully added chapter!");
                                    return res.redirect("/stories/" + story._id);
                                }
                            });
                        });
                    } else {
                        // Add username and ID to content
                        content.author.id = req.user._id;
                        content.author.username = req.user.username;
                        // Save content
                        content.save();
                        story.content.push(content);
                        story.save();

                        req.flash("success", "Successfully added chapter!");
                        return res.redirect("/stories/" + story._id);
                    }

                }
            });
        }
    });
});

// Content Edit Route
router.get("/stories/:id/content/:content_id/edit", middleware.checkContentOwnership, function(req, res){
    Content.findById(req.params.content_id, function(err, foundContent){
        if(err){
            res.redirect("back")
        } else{
              res.render("content/edit", {story_id: req.params.id, content: foundContent})
        }
    })
})

// Content Update 
router.put("/stories/:id/content/:content_id", middleware.checkContentOwnership, function(req, res){
    Content.findByIdAndUpdate(req.params.content_id, req.body.content, function(err, updatedContent){
        if(err){
            res.redirect("back")
        } else {
            req.flash("success", "Successfully edited chapter!")
            res.redirect("/stories/" + req.params.id)
        }
    })
})

Upvotes: 0

Views: 4308

Answers (1)

hardy
hardy

Reputation: 901

While defining a Mongoose Schema,

1 for ascending and -1 for descending

Example:

"use strict";
var mongoose = require('mongoose');
var db= require('mongoose').models;
let findOrCreate = require('findorcreate-promise');

var abc= new mongoose.Schema({
    name: String,
    updated_At: { type: Date, default: Date.now } // like this you can define 
});
mongoose.model('abc', abc);

and you can use this by :


db.abc.find({})
.sort({'updated_At':1})  //1 for ascending and -1 for descending
.exec(Your callback function)

this will make sorting from smallest updated_At date to largest.

Thanks

Upvotes: 1

Related Questions