rch
rch

Reputation: 249

Can't access details of mongoose find() result

Using Node/Express with MongoDB, I'm trying to find if there exists an object with a specific field name.

I think the database connection itself is OK because I can add things into the database just fine (confirmed by running the app then checking via mongo shell)

The following code is supposed to increment field student of Class by 1 and proceed to the next page /nextpage if I get a hit.

exports.join = function(req,res,next){
 Class.find(({code:{$in: [req.body.roomNumber]}}), function(err, out){
  if(err){res.redirect('/'); next(err);}
  else{
   console.log(out);                 // returns the whole object from db. 
                                     // for no match, I get "[]"
   console.log(req.body.formEntry);  // returns the entered form value OK
   console.log(out.roomNumber);      // always returns "undefined"; why?
   if(out != null) {                 // always passes
    console.log('adding 1 to students');
    Class.update({code:req.body.formEntry}, {$inc:{'students':1}}); // also didn't work
    res.redirect('/nextpage');
   }else{
   console.log('class not found');
   }
  }
 };
}

I have tried checking things like out.params.roomNumber (get undefined), or out.next() (thinking it was a query) but I'm rather confused by the output of console.log(out.roomNumber) (ALWAYS undefined) considering the fact that console.log(out) gives me the object I want with all its fields intact. I read a similar question but the problem there was on asynchronosity and as this whole thing is in a callback I think perhaps that's not the case.

Upvotes: 0

Views: 1126

Answers (1)

robertklep
robertklep

Reputation: 203231

find returns an array of results, so out is an array.

If every class has a unique room number, using findOne makes more sense:

Class.findOne({ code : req.body.roomNumber }, function(err, out) {
  // `out` is now a single result, provided there was a match
  ...
});

Also, using $in to match against a single room number is a bit superfluous, so I left it out of the query (similarly to the query you use for update).

As an aside, you shouldn't mix res.redirect() and next() together (because sending a redirect ends the request, but next passes it to other handlers, which will trigger errors in Express). I would suggest using this:

if (err) {
  return res.redirect('/');
}

Upvotes: 1

Related Questions