简体   繁体   中英

Sorting list by chronological order in node.js

Rookie question here:

I am using the Hapi framework and Handlebars for my Node project.

My question is, when a user uploads an item. I'd like for that item to be displayed to them and sorted by date. This might be right but I think I need to pull the time stamp from the db into my view and make a function that orders that time stamp. But I don't know where I would put that function, in my views or somewhere else. Am using a MySQL db

Please Help. Thanks

For a simple sort I would look first to your db. You didn't mention what db you are calling, mongo for instance would look like this:

db.collection.find({ ... spec ... }).sort({ key: datecreated })

That way the data is presorted. Alternatively, if you have your data in your node js action you could use a something like lodash to sort it after pulling from your db into an array, but prior to passing to your view. After doing either of these things, in your view you could just iterate through each value in the array that is pre-sorted on the server side.

https://lodash.com/docs#orderBy

However, if you are looking to have your image appear alongside other images without requiring a new search to the database you probably need a live model system like Angular.

in the item table, set the created_date defaults to CURRENT_TIMESTAMP ; use that to sort in mysql query.

when fetching items to display; use order by created_date .

Unless i'm misunderstanding something in your question.

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