Poh Zi How
Poh Zi How

Reputation: 1569

Meteor-Mongo: Error handling for findone

I am trying to handle errors using findOne in meteor-mongo.

From this stackoverflow question, it appears that I should be able to handle errors by doing collection.findOne({query}, function(err, result){ <handleError> }, but doing so results in an errormessage:

"Match error: Failed Match.OneOf, Match.Maybe or Match.Optional validation"

The following code works:

export default createContainer((props) => {
  let theID = props.params.theID;
  Meteor.subscribe('thePubSub');
  return {
    x: theData.findOne({_id: theID}),
  };
}, App);

The following code does not:

export default createContainer((props) => {
  let theID = props.params.theID;
  Meteor.subscribe('thePubSub');
  return {
    x: theData.findOne({_id: theID}, function(err,result){
      if(!result){
        return {}
      };
    }),
  };
}, App);

What am I doing wrong and how should I be resolving this error? Is this a meteor specific error?

Any help is greatly appreciated!

Upvotes: 0

Views: 972

Answers (1)

ghybs
ghybs

Reputation: 53205

What kind of error are you exactly trying to handle with your callback?

Meteor's findOne is different from node's mongodb driver's findOne that the post you link to uses.

The expected signature is:

collection.findOne([selector], [options])

There is no callback involved, since the method runs synchronously (but is reactive).

If you want to return a default value when the document is not found, you can simply use a JS logical OR:

// Provide an alternative value on the right that will be used
// if the left one is falsy.
theData.findOne({_id: theID}) || {};

A more rigorous approach would be to compare its type with

typeof queryResult === 'undefined'

Note that if theData collection is fed by the above subscription Meteor.subscribe('thePubSub'), I doubt Meteor will have time to populate the collection on the client by the time you query it…

Upvotes: 1

Related Questions