How to create friendly urls using MongoDB / Node.js?

For example, suppose when developing a blog application I want something like

domain.com/post/729

Instead

domain.com/post/4f89dca9f40090d974000001

Ruby has the following

https://github.com/hakanensari/mongoid-slug

Is there an equivalent in Node.js?

+6
source share
3 answers

There are several ways:

1- Assuming you are trying to provide a unique identifier for each blog post. Why not rewrite the "_id" field of your documents in your blog collection? Sample document:

{ "_id" : 122 , "content" : { "title: ..... } 

You will need to look for a method for generating an auto-increment identifier, although this is quite simple. However, this type of primary key is not recommended. http://www.mongodb.org/display/DOCS/How+to+Make+an+Auto+Incrementing+Field

2- Let the _id field remain as it is, and additionally save the "blogid" key, which is an integer, you will need to run ensureIndex in the "blogid" field, at least to quickly access Blogid. Storage overhead will be negligible since you will store the key name and integer in the document more.

Document example:

 { "_id" : xxxxxxxxxx ,"blogid" : 122, "content" : { "title: ..... } 
+1
source

The identifier in MongoDB is actually a hexadecimal value for converting this number to a numerical value, which you can use with the following code to search for a numerical value in the database, for example, 1, 2, 3 .., and this code will convert this value to the corresponding hex

 article_collection.db.json_serializer.ObjectID.createFromHexString(id) 

where article_collection is your collection object

+2
source

There are many projects on GitHub such as https://github.com/dodo/node-slug and https://github.com/stipsan/String.Slugify.js , but they focus on making valid URLs from lines (usually this is a topic topic or article). I have not seen anyone accepting a random number, and some produce a shorter random (?) And unique number.

Personally, I only have a token field in my post object that contains a unique value that is shorter than just using the DB id directly (and a bit more secure). If you use Mongoose, the token can be generated automatically by attaching the pre 'Save' event on your Mongoose model.

+1
source

Source: https://habr.com/ru/post/913896/


All Articles