Ryan Bobrowski
Ryan Bobrowski

Reputation: 2730

MongoDB and URL routing

I have more of a MySQL background than MongoDB, so I'm just trying to figure out best practices for routing based on retrieving data from an API. For example, I want to access the url:

site.com/movies/12

and then load retrieve all of the information from MongoDB about the movie with an id of 12. But Mongo's id is a reference to _id, which is an auto-generated string of characters (certainly not something I want to have in the url). So does this mean I should be creating my own index for every entry in the movies collection? And if so, I would have to call it something other than id, right?

I've seen a lot of examples where they don't include a custom key and I don't really understand it. Certainly they don't want to link to site.com/movies/59e8fdcffeeecb22334fd355 in their app?

Upvotes: 0

Views: 153

Answers (1)

Clement Amarnath
Clement Amarnath

Reputation: 5466

While creating a document if we provide _id as part of our insert statement then the value provided by the user will be taken by mongodb, for this approach all we need to ensure is the _id should be unique value. No worries even if you give a repeated value for _id then we will be getting an error message.

I have a sample collection named stackoverflow and its document having two attributes

db.stackoverflow.insert({ _id:1, movie:"Mission Impossible 1"})
WriteResult({ "nInserted" : 1 })

When I'm trying to insert the same document with same _id then the error message is obtained(Error message as shown in Mongo Shell)

WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 11000,
                "errmsg" : "E11000 duplicate key error collection: test.stackove
rflow index: _id_ dup key: { : 1.0 }"
        }
})

For your scenario if you own the movies collection. We can rewrite the collection with convenient _id matching our requirement.

Please note that updating an _id of a document is not possible, since _id is equivalent to primary key of table row in RDBMS.

So for changing the document _id value, can be done as shown below (creating a new document and deleting the old document)

// Find the document and store it in a variable
doc = db.movies.findOne({_id: ObjectId("5dd45467d55f4d2d2a115502")})

// Give a convenient new _id
doc._id = 1

// Insert the document using the new _id
db.movies.insert(doc)

// Now we will be having two documents for the same movie, so remove the old one
db.movies.remove({_id: ObjectId("5dd45467d55f4d2d2a115502")})

Upvotes: 1

Related Questions