"Cast to Number failed for value \"{ '$lte': '36' }\" (type Object) at path \"profile.age\" for model \"User\""

So I have a mongo schema, which looks something like this:

const UserSchema = new mongoose.Schema({
  profile: {
    // ...other stuff
    age: {
      type: Number,
      min: [18, "Min age is 18"],
      max: [99, "Max age is 99"],
      default: 0,
    },

And Im trying to query it through postman with the following: /users?profile.age[lte]=100

Other queries work, such as users?profile.age=36. This returns the correct number of results.

In my controller I have:

export const getUsers = asyncHandler(async (req, res, next) => {
  let query;
  let queryStr = JSON.stringify(req.query);

  queryStr = queryStr.replace(
    /\b(gt|gte|lt|lte|in|elemMatch|eq)\b/g,
    (match) => `$${match}`
  );

  query = JSON.parse(queryStr);

  const users = await User.find(query);

  if (!users) {
    next(new ErrorResponse(`Unable to get users.`, 500));
  } else {
    res.status(200).json({
      success: true,
      count: users.length,
      data: users,
    });
  }
});

logging the query here gives me { 'profile.age': { '$lte': '36' } } which looks right to me

So basically every time I use lt lte gt gte it throws the following:

CastError: Cast to Number failed for value "{ '$lte': '36' }" (type Object) at path "profile.age" for model "User"

Any help much appreciated.

Thanks!

Edit: I also tried query-to-mongo in case I was handling the query incorrectly but it returns the same error.

Hi @Mo_Ali - Welcome to the community :wave:

CastError: Cast to Number failed for value “{ ‘$lte’: ‘36’ }” (type Object) at path “profile.age” for model “User”

Is it possible that there may be a mismatch in what mongoose is expecting for the query and what was actually passed through for the variable query? The error seems indicates "profile.age" expects a Number but an attempt to cast the object { '$lte': '36' } to a Number fails.

However, I attempted to reproduce this error but so far have not been successful. Would you be able to provide the following information:

  • A self-contained code example that will output this error
  • Mongoose version in use
  • MongoDB version in use

Regards,
Jason

1 Like

Hey @Jason_Tran thanks for responding

Okay so to give some more context, this isn’t just when pulling from the query string:

This does work:

const users = await User.find({
  "profile.age": { $eq: 36 },
});

But this doesn’t:

const users = await User.find({
  "profile.age": { $lt: 100 },
});

Mongoose version 6.5.4. Sorry, how do I check my mongo version?

So yeah, i dont know why, but gt gte lt lte don’t work with find.

This does give the desired result however:

  const users = await User.aggregate([
    {
      $match: { "profile.age": { $lt: 36 } },
    },
  ]);

But I’ve read that find is more performant, and also Im not sure if you can chain other operators with aggregate such as select

Thanks

Hi @Mo_Ali - The behaviour described does sound odd.

On a test environment (you may need to insert the documents i’ve provided), would you be able to run the following code? I have inserted 3 documents to test it against.

Test documents to be inserted:

DB>db.users.find()
[
  { _id: ObjectId("6323d1916b10eece4870dbff"), profile: { age: 20 } },
  { _id: ObjectId("6323d1c634a3c771ab1a8b28"), profile: { age: 15 } },
  { _id: ObjectId("6323d1dc34a3c771ab1a9dc9"), profile: { age: 50 } }
]

Code to test:

import mongoose from 'mongoose';
const mongouri = "CONNECTION_STRING";
const User = mongoose.model('User', mongoose.Schema({
  profile: {
    age: {
      type: Number,
      min: [18, "Min age is 18"],
      max: [99, "Max age is 99"],
      default: 0
    }
  }
}));

const run = async function() {
  await mongoose.connect(mongouri, {useNewUrlParser: true, useUnifiedTopology: true})

  const result = await User.find({
    "profile.age": {$lte: 36}
  });
  console.log(result);

  await mongoose.connection.close()
}()

Please replace `“CONNECTION_STRING” with the test environment connection string you are going to test against and advise of the output.

Note: I’ve reduced the schema to only contain a “profile” field which is an object containing a field called “age”

Sorry, how do I check my mongo version?

If you’re running on Atlas, the version should be stated under “Version” in the Database Deployments screen. Otherwise you can try run:

mongod --version

Regards,
Jason

1 Like

@Jason_Tran do you mean set up a new project locally and try that code? I tried in mongoplayground and what you wrote there works as expected

do you mean set up a new project locally and try that code?

Yes, on the same environment in which you were receiving the error previously. Since the code works elsewhere (including on my machine), I was thinking that the error may be related to the project / code in which the original issue occurred. If you set up a new project and the code works, it may indicate that there may be some incorrect settings in the previous project.

Have you also tried updating to the latest version of mongoose to see if the same error occurs? I believe it is version 6.6.1 as of the time of this message.

Regards,
Jason