3

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

red house 87
  • 1,837
  • 9
  • 50
  • 99
  • You should do something like `_id: mongoose.Types.ObjectId(req.body.invitedTeamID)`, see here https://stackoverflow.com/questions/6578178/node-js-mongoose-js-string-to-objectid-function – Striped Mar 02 '18 at 18:39
  • can you show your Schema of Team – zb22 Mar 02 '18 at 18:47
  • @Striped your method works if it is in fact a valid ObjectId but if it's just a random string it gives me the long and ugly promise error. To handle the ugly promise error in the event that data gets passed to the query that isn't in the format of an ObjectId should I wrap my Await call in a try catch or something? – red house 87 Mar 02 '18 at 18:53
  • Yes, you should always wrap an await with try/catch. – Striped Mar 02 '18 at 18:53

1 Answers1

2

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
  }
}
Wojtek
  • 429
  • 3
  • 11