Muhammad Hamza
Muhammad Hamza Qureshi

Follow

Muhammad Hamza Qureshi

Follow
Creating recent posts with nodejs and mongodb

Photo by Juanjo Jaramillo on Unsplash

Creating recent posts with nodejs and mongodb

Muhammad Hamza's photo
Muhammad Hamza
·Oct 4, 2022·

3 min read

Recently i was asked to create a recent posts feature i was working on and i was asked it should show all the recent posts related to a specific collection of posts.

First let me show you how does the schema looks like for the posts that are being collected

let mongoose = require("mongoose");
const moment = require("moment");
let db = new mongoose.Schema({
  channel_id: String,
  channel_name: String,
  server_name: String,
  user_id: String,
  message: Object,
  synced_at: String,
  synced: {
    type: Boolean,
    default: false,
  },
  timestamp: {
    type: String,
    default: moment().format("DD-MM-YY"),
  },
});

module.exports = mongoose.model("db", db);

pheww, so this is the schema which basically collects and saves discord messages and i needed to create all the recent posts related to a specific server (if you dont know whats discord and you live under the rock then here's an introdcution for you what's discord? & Thank you)

What i did was to fetch a specific server by its name (can be done either way name or id) and then fetch all the recent entries that were made recently in the mongodb, Now here i had two options to go with,

First Option: Fetch all records with specific server name and filter them using the timespan.

Second Option: Fetch all the recent records created in mongodb with a filter of specific server.

I choose the second option because i didn't have to do too much i just wrote a mongoose query that did the job for me and i applied a specific filter or condition and there was this one other filter as well which was if the record is synced or not?


/**
 * @method get
 * @Route /view-server
 * @description show a list of all servers added
 */

router.get("/view-server/:server", async (req, res) => {
  //fetching the latest posts
  let timestamps = await db.find({ server_name: req.params.server });

  //clear up the latest posts
  let latest_posts = timestamps.filter(function (a) {
    var key = a.synced_at + "|" + a.channel_name;
    if (!this[key]) {
      this[key] = true;
      return true;
    }
  }, Object.create(null));

  //fetch recent posts

  let posts = await db
    .find({ server_name: req.params.server, synced: true })
    .sort({ _id: -1 })
    .limit(20);

  //clear up the latest posts
  let result = posts.filter(function (a) {
    var key = a.timestamp + "|" + a.channel_name;
    if (!this[key]) {
      this[key] = true;
      return true;
    }
  }, Object.create(null));

  channels_to_sync
    .find({ server_name: req.params.server })
    .then(async (channels) => {
      res.render("viewserver", {
        timestamps: latest_posts,
        channels: channels,
        server: req.params.server,
        recent_posts: result,
      });
    });
});

So this code above fetches all the latest or recent posts and makes sure to render that with the page and on the other side of the page it just adds a link to the recent post date or key so its a href link which should lead to all the posts that were in that specific time or were recently created.

 <%for(let x=0; x < recent_posts.length; x++){%>
                  <a href="/all-posts/<%= recent_posts[x].channel_id%>/<%= recent_posts[x].timestamp%>" class="p-2"><%= recent_posts[x].channel_name%> <%= recent_posts[x].timestamp%></a>
 <%}%>

The above code shows the recent posts which looks like this,

Screenshot from 2022-10-04 11-03-19.png

and if clicked on that recent post it should show the recently created records relating to that specific channel id (a primary key).

Screenshot from 2022-10-04 11-04-10.png

Which looks like something similar to above and you might wonder why this kind of format because its a discord backup webapp that i wrote recently.

You might also wonder there are latest and recent posts and what's the difference?

well recent posts are records created recently in the database and the other ones are similar just fectched within a timespan which is specific and rendered to frontend.

Thanks for reading this and at this point if you have questions in your mind you can let me know i would love to answer and if you dont have i think you are superior to all the devs out there cause im myself confused now even after writing this article and i myself wrote the code.

Till next time :)

 
Share this