question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Error: Can't use $x with Number.

See original GitHub issue

Any advice on trying to handle the validation on invalid query operator?

// The `amount` below is set as Number  

Transaction
  .find({ amount: { '$x': 42 } }) // note the intended invalid query operator here
  .then(() => {
    // ...
  })
  .catch((err) => {
    console.log(err); // log below
    if (err instanceof CastError) {
      // handle if cast error
    }

    return next(err);
  });

The log is:

Error: Can’t use $x with Number. at SchemaNumber.castForQuery (/…/node_modules/mongoose/lib/schema/number.js:278:13)

The err is not an instance of CastError so I don’t know how to specifically check the error above on mongoose. Currently, I set it as error 500 but I want it to change to something more specific error. Thanks!

Mongoose: v5.0.3 Nodejs: v8.9.3 Mongodb: v3.6.3

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
lineuscommented, Aug 29, 2018

@vkarpov15 should we create a specific Error type to throw for this instead of the vanilla Error that’s currently thrown? This seems like an edge case, otherwise I’d have done it already.

@ctrlnot If you want to test for this specific error condition now, you could do so in a pre query hook, and return an Error you can test in your handler. Here is an example:

6927.js

#!/usr/bin/env node
'use strict';

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
const conn = mongoose.connection;
const Schema = mongoose.Schema;

const schema = new Schema({
  amount: Number
});

schema.pre('findOne', function (next) {
  let validKeys = Object.keys(this.schema.path('amount').$conditionalHandlers);
  let keys = Object.keys(this.getQuery().amount);
  let badKeys = '';
  for (let key of keys) {
    if (!validKeys.includes(key)) {
      badKeys += ` ${key}`;
    }
  }
  if (badKeys.length) {
    let msg = `${badKeys}`;
    msg += badKeys.trimLeft().split(' ').length > 1
      ? ' are not valid conditions'
      : ' is not a valid condition';
    return next(new Error(msg));
  } else{
    next();
  }
});

const Test = mongoose.model('test', schema);

const test = new Test({ amount: 42 });

async function run() {
  await conn.dropDatabase();
  await test.save();
  await Test.findOne({
    amount: { $x: 5, $y: 10, $z: 15 }
  }).catch(handleConditionError);
  await Test.findOne({ amount: { $a: 42 }}).catch(handleConditionError);
  let found = await Test.findOne({ amount: { $gte: 41 } });
  console.log(found);
  return conn.close();
}

run();

function handleConditionError(e) {
  if (/not (a )?valid condition/.test(e.message)) {
    // send back http 400 Bad Request
    // return res.status(400).json({ err: e.message }) etc etc
    console.error(`400: Bad Request:${e.message}`);
  } else {
    // return res.status(500).json({ err: 'whoops' }) etc etc
    console.error('500: Something else went wrong');
  }
}

Output:

issues: ./6927.js
400: Bad Request: $x $y $z are not valid conditions
400: Bad Request: $a is not a valid condition
{ _id: 5b868927bc07590988fd2fb8, amount: 42, __v: 0 }
issues:
0reactions
lineuscommented, Aug 29, 2018

you bet 👍

Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeError: can't assign to property "x" on "y": not an object
In strict mode, a TypeError is raised when attempting to create a property on primitive value such as a symbol, a string, a...
Read more >
What can I do about "ImportError: Cannot import name X" or ...
I'm assume the error is due to importing entity twice - once in main.py and later in physics.py - but how can I...
Read more >
"Windows cannot access the specified device, path, or file ...
Troubleshooting error message: Windows cannot access the specified device, path, or file. You may not have the appropriate permission to access the item....
Read more >
If you can't send or receive messages on your iPhone or iPad
In the Settings app, tap Messages. Turn iMessage off and then back on. Tap Send & Receive. Tap the phone number that you...
Read more >
Number Keys not Working in Windows 10 - 1 Simple Fix
Number keys not working in Windows 10? Unable to use numberic pad in windows 10? ... Your browser can't play this video.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found