Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create friendly URLs with MongoDB/Node.js?

For example suppose in designing a blog application I want something like

domain.com/post/729

Instead of

domain.com/post/4f89dca9f40090d974000001

Ruby has the following

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

Is there an equivalent in Node.js?

like image 874
deltanovember Avatar asked Apr 23 '12 04:04

deltanovember


People also ask

How do I create a URL in node JS?

Access Webpage through URL in NodeJS Now, your server will run at PORT 8100 and URL will be http://localhost:8100 if local machine, else will be your live URL. Step 3 : Create html file which you want to access through URL. For example, if your URL is http://localhost:8100/home.html. Then create a file home.

How do I link my node JS to MongoDB?

To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });


2 Answers

The id in MongoDB is actually a hexadecimal value to convert that into a numerical value you can use the following code to search for numerical value in the database like 1, 2, 3.. and this code will convert that value into appropriate hex

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

where article_collection is your collection object

like image 98
lakkadshaw Avatar answered Oct 31 '22 16:10

lakkadshaw


There are a few ways :

1- Assuming you are trying to provide a unique id to each blog post . Why not overwrite the '_id' field of your documents in the blogs collection ? Sample document would be :

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

You will have to look out for a method to generate an autoincrement id though, which is pretty easy. This type of primary keys are however 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 additionaly store a key 'blogid' which is an integer, you will have to run ensureIndex on 'blogid` field though to make access by blogid fast. Storage overhead would be minor, as you will be storing a keyname and an integer more in your document.

Sample document would be :

{ "_id" : xxxxxxxxxx ,"blogid" : 122, "content" : { "title: ..... }
like image 25
DhruvPathak Avatar answered Oct 31 '22 15:10

DhruvPathak