Shane D'Silva
Shane D'Silva

Reputation: 453

Can't retrieve documents from MongoDB

I'm trying to retrieve my documents from mongo db.

I make an ajax get request to my node server and the server is supposed to find the documents according to the "breed" variable, put it in a list and send it back to the client.

Then in the success part of ajax, I'm to populate a listview with the list.

The problem is that the find() functions returns null I believe even though I have one document in my collection that satisfies the condition.

Here is how I'm retrieving the documents:

function search(req,res){
  var merr = mongoerr400(res)

  var breed
  if  (req.params.query == "Foghorn")
  breed={breed:"Foghorn"};
  else if  (req.params.query == "Hawk")
  breed = {breed:"Hawk"};
  else if (req.params.query == "Tweety")
  breed = {breed:"Tweety"};
  else if (req.params.query == "Little")
  breed = {breed:"Little"};
  else if (req.params.query == "Bertha")
  breed = {breed:"Bertha"};

  try{
    mongo.coll(
      'chicken',
      function(coll){
        coll.find(
          {breed},
          merr(function(cursor){
            var list = []
            cursor.each(merr(function(chicken){
              console.log(chicken);
              if( chicken ) {

                var item = {
                  _id: chicken._id,
                  id: chicken.id,
                  dateTime: chicken.dateTime,
                  latitude: chicken.latitude,
                  longitude: chicken.longitude,
                  weight: chicken.weight,
                  eggs: chicken.eggs,
                  grain: chicken.grain,
                  category: chicken.category
                }

                list.push(item);
              }
              else {
                common.sendjson(res,{ok:true,list:list})
              }
            }))
          })
        )
      }
    )
  }
  catch (err) {
    console.log('Error writing to the file: ' + err.message)
    res.sendStatus(500);
  }
}


mongo.coll = function(name,win,fail){
  mongo.db.collection(name,mongo.res(win,fail));
}

The console.log(chicken) returns null in the console as a result it's sending a null list to my client.

An example of my document in mongodb. Any idea why?

Upvotes: 0

Views: 470

Answers (1)

Krishna
Krishna

Reputation: 116

  1. First param in 'find( )' should be an object like {breed:"Hawk"} ( remove those flower-braces to 'breed' )
  2. 'common.sendjson( )' should not be in that 'else' statement. Move it to somewhere below such that after all retrievals into the 'list', it will send them to the client.

Upvotes: 1

Related Questions