1

I am looking at this article as I want to create a Comments System with Nodejs and MongoDB:

https://docs.mongodb.org/ecosystem/use-cases/storing-comments/

There are 3 methods to implement a comments system as it mentioned in this article, and the 1st method is to save a comment as a single document.

In the 1st method, the article uses a "slug" (for example, '34db') for each comment that is going to be saved in MongoDB. This "slug" is used to sort the comments, so it must be unique.

My question is, given the situation that when the comment is being created, the _id of the comment (MongoDB assigns an Object.id automatically to a saved object ) is unknown, how can we create such an unique "slug" for the comment that we are going to save?

In the article mentioned above, it uses a pseudo-method called "generate_pseudorandom_slug()". And I wonder how we can implement such an method in the real situation, to get something unique like "34db" for a comment?

Thank you!

Luke
  • 93
  • 1
  • 6

1 Answers1

0

I know this is posting is old, but here is my solution that takes in the function that inspired used. It is for threaded comments, and gathers the concepts provided in the referenced MongoDB article. I have this code in my models/comment.js path and will most likely pull the generateSlug() function out to a utils.js file and import it back in.

function generateSlug() {

  let slug = '';
  let chars = 'abcdefghijklmnopqrstuvwxyz0123456789';

  for ( let i = 0; i < 5; i++ ) {
    slug += chars.charAt(Math.floor(Math.random() * chars.length));
  }

  return slug;
}

CommentSchema.pre('save', function (next) {
  let comment = this;
  let timestamp = moment(comment.postedAt).format('YYYY.MM.DD.hh:mm:ss');
  let slug_part = generateSlug();
  let full_slug_part = timestamp + ':' + slug_part;

  if ( comment.parent_id ) {
    Comment.findOne({'_id': comment.parent_id }, { slug: 1, full_slug: 1 })
      .then(parent => {
        comment.slug = parent.slug + '/' + slug_part;
        comment.full_slug = parent.full_slug + '/' + full_slug_part;
        next();
      });
  } else {
    comment.slug = slug_part;
    comment.full_slug = timestamp + ':' + slug_part;
    next();
  }
});
Ross Sheppard
  • 850
  • 1
  • 6
  • 14