1

Im trying to make a greater than query but it always returns an empty array.

    const productSchema = require("./productsSchema");
const getProductsGreaterThan = async (minimum_id) => {
try{
    console.log(minimum_id);
    const productById = await productSchema.find({id: {$gt:minimum_id}});
    return productById
}
catch(err){
    console.error(err);
}
}

This is my controller:

if (req.params.minimum_id) {
    const productsById = await productsModel.getProductsGreaterThan(req.params.minimum_id);
    res.status(200).json(productsById);
}

It should return the products with an ID greater than what i type in the req.params...

routes.get("/products/:minimum_id?",productRoutes.getProductsGreaterThan);

But when i write the route like this in the url it gives me an empty array => http://localhost:3000/products/10 What is wrong with this code? Im very confused, because other queries like find({}) work. My mongoose version is 6.2.10.

3
  • Have you tried const productById = await productSchema.find({id: {$gt:parseInt(minimum_id, 10)}});? Commented Apr 12, 2022 at 14:09
  • I just tried, but its not working :( It gives me an empty string aswell Commented Apr 12, 2022 at 14:50
  • Would be helpful if you can provide your sample dataset. A common error is filtering on incorrect field, such as filtering on id instead of _id Commented Apr 12, 2022 at 16:48

3 Answers 3

4

Solved. Somehow the problem was in the name of the collection of mongoDB. It seems it should be always in lower-case and plural.

Sign up to request clarification or add additional context in comments.

1 Comment

Crazy. 's' is required in collection names. c.f. stackoverflow.com/questions/10547118
2

I solved my issue by changing MongoDB table name. The problem was in the name of the collection of mongoDB. Your table names should be always in lower-case and plural (this was most critical thing in my case). Maybe you can try this.

Comments

1

If you are using mongoose and MongoDB the correct id format is _id. So you would do the following:

productSchema.find({_id: {$gt:minimum_id}})

1 Comment

Yeah, but that id is one I put in the Schema. Not the authomatic one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.