red house 87
red house 87

Reputation: 2415

Mongoose - How to handle empty results

I'm fairly new to Mongo DB/ Mongoose and want to be sure i'm approaching Mongoose errors the correct way. I'm trying to search for a document by its' _id. Here is my query:

const team = await Team.findOne({_id:req.body.invitedTeamID});

This works fine but I need to validate if any record was returned from this query so after a bit of research I amended it to be like so:

const team = await Team.findOne({_id:req.body.invitedTeamID}, function(err, doc){
  if(doc.length === 0 || err){
    console.log("no record found!")
  }
});

When I enter a bogus object id for the invitedTeamID variable I get an ugly Mongoose rejected promise error saying something like:

CastError: Cast to ObjectId failed for value "005a99

This happens for either or of the above functions and I don't get my console.log statement.

Can someone please advise what's the correct way to handle this?

Thanks

Upvotes: 3

Views: 2434

Answers (1)

Wojtek
Wojtek

Reputation: 439

First of all, you can use shortcut method Model.findById() to query by ObjectId. Secondly, you are mixing async function and callback function. There are three things you need to add to your method:

  1. Validation of ObjectId
  2. Check for returned value of the query
  3. Error handling

Revised method would look like this:

const mongoose = require('mongoose');
const Team = require('../models/Team');

async function getTeamById(id) {
  if (!mongoose.Types.ObjectId.isValid(id)) {
    // handle bad id
  }
  try {
    const team = await Team.findById(id);
    if (!team) {
      // no team with such id, error handling code
    }
    // team was obtained, rest of the code
  } catch (error) {
    // handle query error
  }
}

Upvotes: 2

Related Questions