[Help] MongoDB: find or insert

[Help] MongoDB: find or insert
0.0 0



I have a question regarding MongoDB. I’m currently in the URL shortener exercise. I have a collection named urls and this collection has 2 parameters: “original_url” and “short_url”.
I want to do a find on this collection by “original_url” and if it doesn’t find anything, then I want to insert a new document. This is a simplified version of the code I have:

collection.find({ original_url: param }).toArray(function(err, document) {
if (document.length == 0) {
var object = {
"original_url": param,
"short_url": shortUrl 
collection.insert(object, function(err, newObj){
if (!err) {

Everytime this part of the code runs, I get an error:

{ [MongoError: server instance pool was destroyed]
name: ‘MongoError’,
message: ‘server instance pool was destroyed’ }

I understand that I get this error because the .find and .insert are nested.
Is there any other way to do something like “find or insert”?
I tried to search for this, but couldn’t find anything.
I’m aware of the .update with upsert: true, but how can I apply this to my case if I don’t want to update the document?
You can check my code in https://github.com/flaviarodriguesf/fcc-url-shortener
And the app: https://url-shortener-00.herokuapp.com/

Thanks in advance for the help


Try to move your db.close() at the end of else and else if loops:


I was able to fix the problem by using the .update with upsert: true:

                { original_url: param },
                { $setOnInsert: { short_url: randomNumber.toString() } },
                { upsert: true },
                function(err, doc) {
                    if (err) {

It seems to be working now, except for the redirect. Here’s how I’m doing it:
response.redirect(200, document[0].original_url);

I always get “OK. Redirecting to www.google.com”, but it never really redirects. I also tried without specifying the status code, but it doesn’t work.


Your code should work if you remove the status code 200.
Maybe try to re-upload to Heroku or set the status code explicitly to 302


I removed the status code 200 but then started to get the error “too many redirects”. So I decided to create an app.get only for the short urls (which are always random numbers). Then the redirects were not working correctly because some urls didn’t have http/https. But now it seems to be working correctly, at least I hope.

Thanks for the help @jenovs