T
T
tikos2015-12-06 22:11:15
JavaScript
tikos, 2015-12-06 22:11:15

How to take specific value from mongodb base?

Hello. Here I have certain data in mongodb for example :

{"_id":"56647d86d9742e5c1cce4023","longurl":"http://mongoosejs.com/docs/index.html","shorturl":"KoQrG","__v":0}

and here is the get request:
app.get('/url/:url', function(req,res){
    urls.find({shorturl : req.params.url}, function(err,result){ //urls - это сама база с данными.
        if (err) res.json(err);
         else res.redirect(result.longurl); //вот тут я хочу перейти на другую страницу
    });
  });

So that's how I try to go there, then it writes to me
Loop redirect detected on this page

I just tried to do this res.send (result.longurl) but it doesn’t output anything, and when it’s just res.send (result) it displays all the values ​​​​of this field (_id, longurl, shorturl, _v) but I need to refer specifically to longurl to this field and take its value? how to do it?
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pydeg, 2015-12-07
@Pydeg

You have a cyclic redirect due to the fact that the base returns an empty array, instead of longurl an empty string and the page starts to be updated cyclically.
And the error is that after returning the data from the database, you need to check that they are there:

app.get('/url/:url', function (req, res){
    urls.find({shorturl : req.params.url}, function (err, result){ //urls - это сама база с данными.
        if (err) return res.json(err);

        if (result.length > 0) {
              if ('longurl' in result) {
                      res.redirect(result.longurl); //вот тут я хочу перейти на другую страницу
              } else {
                    res.json('Longurl is not exists');
              }
        } else {
              res.json('No data');
        }
    });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question