MongoDB check if a url exists in another document before adding

Hey, thanks for reading this. I am kinda confused as to the best way to store data for urls in the url shortener microservice. Basically, here is what I am trying to accomplish:

[{
  "_id": ObjectID("awhdoia"),
  "url": "https://google.com/"
},
{
  "_id": ObjectID("awdawdawd"),
  "url": "youtube.com"
}]

and the relevant code:

function newUrl(db, url, callback) {
  id = shortid.generate();
  db.collection('urls').insertOne({"_id": id, "url": url}).then(results => callback())
}

this is all fine and dandy, but then I end up getting something like this:

[{
  "_id": ObjectID("awhdoia"),
  "url": "https://google.com/"
},
{
  "_id": ObjectID("awdawdawd"),
  "url": "youtube.com"
},
{
  "_id": ObjectID("awdawd"),
  "url": "youtube.com"
},
{
  "_id": ObjectID("awdadawdawdawda"),
  "url": "youtube.com"
},
{
  "_id": ObjectID("awdawdawdawdawdawdaawda"),
  "url": "youtube.com"
},
{
  "_id": ObjectID("a"),
  "url": "youtube.com"
},
{
  "_id": ObjectID("dawda"),
  "url": "youtube.com"
},]

you get the point.

Use a find query first.

Pseudo:

Urls.find( { URL: url } ).toArray()…blah blah blah

If that returns [] then insert the new record, if it returns an element in the array, return that to the user instead.

1 Like

Awesome! I’ll try it out tomorrow, looks like that’s the best way to do it! Thanks :smiley: