While the find operation in mongoose failed to return any documents, the compass tool was successful in retrieving them

Objective

To retrieve products based on category id from the 'products' collection in MongoDB using mongoose.find method.

Expected Outcome vs. Actual Outcome

The expected result is to receive all documents matching the specified category within the given limit, but instead, an empty array is returned. I tested querying with MongoDB's Compass and found it to work as intended. However, when attempting to find documents by id (successful), title (successful), and price (unsuccessful) in my code, I couldn't identify the root cause of the problem.

Code Implementation

Defining product schema and model:

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  thumbnail: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  category: {
    type: mongoose.Types.ObjectId,
    required: true,
  },
  rating: {
    type: Number,
    default: 0,
  },
  voters: {
    type: Number,
    default: 0,
  },
});

.
.
.

const Product = mongoose.model('product', productSchema);

module.exports = { Product, ... };

Resolver logic:

products: (_, { limit, category }) => {
      console.log(mongoose.Types.ObjectId('5ec120a9fc13ae248f000004')); // Successfully logs
      Product.find({ category: mongoose.Types.ObjectId(category) }) // Tried with simple string, but didn't work
        .limit(limit)
        .exec((err, products) => {
          if (err) console.log(err);
          console.log(products);
        });
      if (category) return Product.find({ category }).limit(limit);
      return Product.find({}).limit(limit);
    },

Console output:

5ec120a9fc13ae248f000004
[]

Example data in 'products' collection:

{
    "_id": {
        "$oid": "5ec129e55db26438fcdb9b01"
    },
    "title": "Ecolab - Lime - A - Way 4/4 L",
    "category": "5ec120a9fc13ae248f000004",
    "thumbnail": "https://source.unsplash.com/350x390/?Automotive",
    "price": "236.13",
    "rating": 878210,
    "voters": 2668388
},
{
    "_id": {
        "$oid": "5ec129e55db26438fcdb9b02"
    },
    "title": "Mushrooms - Black, Dried",
    "category": "5ec120a9fc13ae248f000001",
    "thumbnail": "https://source.unsplash.com/350x390/?Sports",
    "price": "439.85",
    "rating": 549879,
    "voters": 2375685
},
{
    "_id": {
        "$oid": "5ec129e55db26438fcdb9b03"
    },
    "title": "Dried Figs",
    "category": "5ec120a9fc13ae248f000004",
    "thumbnail": "https://source.unsplash.com/350x390/?Automotive",
    "price": "202.60",
    "rating": 925701,
    "voters": 2740499
}

Answer №1

To summarize: Ensure that you convert the data in the price and category fields of your database to be of type Number and ObjectId.

When using Mongoose to query data, it is important that data types are consistent throughout:

  1. Make sure that the data types of the field being queried align with your schema

In cases like aggregation, where mongoose may not automatically infer types, it is recommended to perform the conversion manually to avoid any unexpected issues.

  1. Confirm that the data types of the actual data stored in the database match what is specified in your schema

If there have been updates to your schema, ensure that the data is migrated and converted accordingly. Mongoose may handle conversions at times, but if the stored data does not align with the schema, it could lead to inconsistencies during queries.

Upon reviewing your database output, we observe that "price": "236.13" and

"category": "5ec120a9fc13ae248f000004"
are saved as Strings instead of the expected Number and ObjectId. Comparing this to "rating": 878210 and
"_id": { "$oid": "5ec129e55db26438fcdb9b01" }
, we see how Number and ObjectId should be represented.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js for Streaming Videos

I am currently working on streaming video using node.js and I recently came across this helpful article. The setup works perfectly when streaming from a local source, but now I need to stream the video from a web source. However, my specific requirement i ...

Steps to invoke another service (function) prior to calling the res.view() function in sails JS:

I am looking to execute a separate function, like a Service function, before Sails renders the page into HTML. Please refer to the controller code below... var MYController = { index: function(req, res, next) { req.flash("error", "Testing hello ...

Encountering a strange issue when attempting to link app.js with mongodb

I recently set up MongoDB and the Compass, everything was working fine until I tried to connect MongoDB with my app.js. Now I'm getting a strange error message. Could anyone help me understand what this error means and how I can fix it? Unfortunately, ...

Can you provide guidance on securing a REST API using Google authentication?

I'm currently working on developing a REST API using NodeJS and Passport for a single-page JavaScript application. I am struggling to find the right approach to securing my REST API with Google OAuth. Can someone guide me on how to achieve this? Any ...

In one application, there are two connections established with mongoose. The purpose of the second connection is to establish a dependency on the

Seeking advice: I am facing an issue where I need to establish two separate connections to the database. The first database contains login information, while the second holds all other relevant data. Can this be achieved through integration of Node.js, m ...

"MongoDB's .find function functions properly in the shell environment, but encounters issues when

As a newcomer to Node Express Mongo, I decided to venture into creating my own website after following tutorials. The page I'm working on is a login page. While other people's code has worked for me, my attempt didn't go as planned. Even con ...

Express JS causing NodeJS error | "Issue with setting headers: Unable to set headers after they have been sent to the client"

As I embark on my journey to learn the fundamentals of API development, I am following a tutorial on YouTube by Ania Kubow. The tutorial utilizes three JavaScript libraries: ExpressJS, Cheerio, and Axios. While I have been able to grasp the concepts being ...

Searching in sequelize for a specific date using a clause

Operating System: Linux (Lubuntu) Programming Language: Javascript (Node js) Framework: express js Database: mysql "data" represents a Date field from the "activitat" table Upon running this query using Sequelize.js models.TblActivitat.findAll( ...

What was the reason for node js not functioning properly on identical paths?

When the search route is placed at the top, everything works fine. However, when it is placed at the end, the route that takes ID as a parameter keeps getting called repeatedly in Node. Why does this happen and how can it be resolved? router.get('/se ...

Condense items into objects and arrays when the Express query yields multiple objects in a many-to-many query

I have a situation where my SQL queries are returning multiple objects due to a many-to-many mapping in express. I am in search of a tool that can help me simplify these common objects by nesting arrays of objects within them. SELECT * FROM User LEFT JOIN ...

Embrace the flexibility of using Next.js with or without Express.js

Recently, I started the process of migrating a project from create-react-app to next.js. However, I am facing uncertainty when it comes to migrating the backend of the project. Currently, my backend is built with an express server. In next.js, there are p ...

Exploring request parameters within an Express router

I'm currently facing an issue with accessing request parameters in my express router. In my server.js file, I have the following setup: app.use('/user/:id/profile', require('./routes/profile')); Within my ./routes/profile.js fil ...

Should you consider using the Singleton pattern in Node.js applications?

After stumbling upon this specific piece discussing the creation of a singleton in Node.js, it got me thinking. The require functionality according to the official documentation states that: Modules are cached after the first time they are loaded. Multi ...

Ensuring Node.js backend JavaScript waits for completion of my bash script before proceeding

Running three bash commands through a Node.js code snippet. Here's a portion of the script: exec(str, function(error, stdout, stderr){ console.log('stdout:'+stdout); console.log('stderr:'+stderr); if(error!=null){ ...

Escape a "for" loop from within a callback function in Node.js

My objective with the code snippet below is to exit FOR LOOP B and continue with FOR LOOP A by utilizing a callback function. for(var a of arrA) { // ... // ... for(var b of arrB) { // ... // ... PartService.getPart(a ...

Customizing response headers in vanilla Node.js

My Node.js setup involves the following flow: Client --> Node.js --> External Rest API The reverse response flow is required. To meet this requirement, I am tasked with capturing response headers from the External Rest API and appending them to Nod ...

My Express server is having trouble loading the Static JS

I'm feeling frustrated about this particular issue. The problem seems to be well-solved, and my code looks fine, but I can't figure out what's wrong . . . I have a JavaScript file connecting to my survey page, which I've added at the b ...

The ajax client is encountering an undefined response, but it is correctly processed when accessed through the

I am in the process of setting up an ajax client with a dummy server for testing purposes. I have successfully resolved the cors issue, but now I am facing a problem where the response from the ajax client is showing as undefined. Interestingly, when I acc ...

Is there a way to retrieve MongoDB count results in Node.js using a callback function?

Is there a way to access mongodb count results in nodejs so that the outcome can be easily retrieved by asynchronous requests? Currently, I am able to retrieve the result and update the database successfully. However, when it comes to accessing the varia ...

How can you identify duplicate entries using Mongoose?

I am currently working on a create function and encountering some code that closely resembles this: if(req.body.test !== undefined) { if(--req.body.test EXISTS IN test (model)--) { DO STUFF } else { ...