edu
edu

Reputation: 53

Querying with .toArray won't return any results to view

Trying to return all the 'titles' of the news. It is not returning anything to frontend. What's the problem?

var table = [];

router.get('/api/v1/news', function (req, res) {

   var title = req.params.title;

   News.find({title: title}).toArray(function (err, news) {

      if (err) {
          res.send('error');
      } else if (news.length > 0){

          //table.push(news);
          News.on('row', function (row) {
              table.push(row);
          });

          // After all data is returned, close connection and return results
          News.on('end', function () {
              done();
              return res.json(table);
          });
      }
    });
});

UPDATE:

Okay, it does NOT return any values. This is how it looks in database:

{
    "_id": {
        "$oid": "592142b13257303488922eb2"
    },
    "date": "21-05-2017",
    "text": "noniin",
    "title": "moi",
    "__v": 0
},

{
    "_id": {
        "$oid": "59217776697b07245cc7d87f"
    },
    "date": "21-05-2017",
    "text": "hgggg",
    "title": "thghfg",
    "__v": 0
}

Collection name is News. I can get all data out without specifying to query 'title', but with it, nothing.

Am I understanding req.params wrong? News collection -> find from inside the collection, all 'titles'and return them to view.

Upvotes: 3

Views: 73

Answers (3)

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20108

you should change the /api/v1/news to /api/v1/news/:title

var table = [];

router.get('/api/v1/news/:title', function(req, res) {

    var title = req.params.title;

    News.find({
        title: title
    }).toArray(function(err, news) {

        if (err) {
            res.send('error');
        } else if (news.length > 0) {

            News.on('row', function(row) {
                table.push(row);
            });

            News.on('end', function() {
                done();
                return res.json(table);
            });
        }
    });
});

Upvotes: 0

chetan mekha
chetan mekha

Reputation: 685

Try with below solution and pass the parameter in body,

    router.get('/api/v1/news', function (req, res) {
    var title = req.body.title;
  return News.find({title : title},function (err, title) {
    if (!err) {
      return res.json({ status: 200, message: "success", data: title});
    }
    else {
      return res.json({ status: 500, message: "failure" });
    }
  });
});

Upvotes: 0

Jyotman Singh
Jyotman Singh

Reputation: 11340

I think you're confusing req.params with req.query. If your request URL is of the form -

http://host/api/v1/news?title=something

Then the value of title will be available in req.query.title.

Otherwise if it's of the form -

http://host/api/v1/news/:title

Then the value of title will be available in req.params.title.

Upvotes: 3

Related Questions