Navigating and exploring data stored in a mongoose database

Currently, I am attempting to filter data based on a specific id (bWYqm6-Oo) and dates between 2019-09-19 and 2019-09-22. The desired result should return the first three items from the database. However, my current query is returning an empty array. I would appreciate any assistance in resolving this issue. Thank you!

var findBy = {
    _id : bWYqm6-Oo,
    exercises : [
      {
        date: {
          $gte: 2019-09-19,
          $lt: 2019-09-22
        }
      }
    ]
  }
  UserModel.find(findBy).limit(5).exec((err, data) => {
      (err) ? res.json({"error" : "problem searching for exercises: " + err}) :  res.json(data);      
  });

The structure of my database:

{
    _id: "bWYqm6-Oo",
    user: "rommy",
    exersises: [
        {
        user_id: "bWYqm6-Oo",
        date: "2019-09-20T00:00:00.000Z",
        description: "stiup",
        duration: "22",
        _id: "pu90D-dHx"
        },
        {
        user_id: "bWYqm6-Oo",
        date: "2019-09-21T00:00:00.000Z",
        description: "pushup",
        duration: "22",
        _id: "YtfsJLOXb"
        },
        {
        user_id: "bWYqm6-Oo",
        date: "2019-09-20T00:00:00.000Z",
        description: "stiup",
        duration: "22",
        _id: "pu90D-dHx"
        },
        {
        user_id: "bWYqm6-Oo",
        date: "2019-09-24T00:00:00.000Z",
        description: "stiup",
        duration: "22",
        _id: "pu90D-dHx"
        }
    ],
    __v: 9
}

In my server.js file, here is where I call my files:

Answer №1

Just a few points to consider:

In MongoDB, the _id field for a document is always unique, so including it in your query like this:

var findBy = {
    _id : bWYqm6-Oo,
    exercises : [
      {
        date: {
          $gte: 2019-09-22,
          $lt: 2019-09-22
        }
      }
    ]
  }

The section regarding the 'exercises' array with a date range filter seems unnecessary since there will only be one document with the _id of 'bWYqm6-Oo'.

If you want to query based on a date range, you can simplify it by using a structure like this:

var query = {
  'exercises.date': {$gte: '2019-09-22', $lt: '2019-09-22'}
}

I hope this clarifies things for you.

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

What could be causing the malfunction in one of the functions within my JavaScript code?

As a JavaScript beginner, I am currently working on creating a To-do App with JavaScript. Most of the functions are functioning perfectly except for one called doneTask at line 36. Despite numerous attempts to identify the issue, I have been unsuccessful s ...

The solution to enabling multiple inputs when multiple buttons are chosen

Below is a link to my jsfiddle application: http://jsfiddle.net/ybZvv/5/ Upon opening the jsfiddle, you will notice a top control panel with "Answer" buttons. Additionally, there are letter buttons, as well as "True" and "False" buttons. The functionali ...

What is causing Puppeteer to not wait?

It's my understanding that in the code await Promise.all(...), the sequence of events should be: First console.log is printed 9-second delay occurs Last console.log is printed How can I adjust the timing of the 3rd print statement to be displayed af ...

Leveraging the power of Framer Motion in combination with Typescript

While utilizing Framer Motion with TypeScript, I found myself pondering if there is a method to ensure that variants are typesafe for improved autocomplete and reduced mistakes. Additionally, I was exploring the custom prop for handling custom data and des ...

Remove duplicate elements from a JSON array

How can I add each item in an array for each duplicate? Transform: [ { "uuid":"EE877ABD-932F-4B4C-AB23-B324363B0B60", "planning":[ { "uuid":"6D680178-9B05-4744-A004-163D4B3E1E84", "star ...

Issue with react-addons-css-transition-group and multiline TextFields in Material-UI TextField

If a TextField with multiline is nested inside a react-addons-css-transition-group, it seems to disrupt the show transition. Any suggestions on how to handle this situation effectively? Check out my code snippet here: https://codesandbox.io/s/material-dem ...

The browser is unable to load the local JSON file due to an XMLHttpRequest error

I have been attempting to import a json file into a table, after conducting thorough research I finally discovered some solutions on how to achieve this. However, when trying to implement it in Chrome, I encountered the following error: XMLHttpRequest ...

Conditionally displaying an input model in Vue.js using v-if

Just starting to learn vue.js and I'm looking to display table data. My idea is that when the table is in display mode, it should only show the data. However, when I click on the edit button of a table row, I want that specific row to switch to edit m ...

Error in test runner: Cannot convert type 'Cucumber' to type '? extends Runner' in Java cucumber

I'm currently working on setting up the Cucumber framework using Java for running my tests, but encountering a type mismatch error in the Test Runner. package cucumbertest; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import ...

The JavaScript function's if and else statements are being executed simultaneously

Upon loading the page, I am checking the value of a dropdown. Strangely, when I debug, it appears that the controller is executing both the if and else statements, which should not be happening. /* Here is my code: */ $(window).load(function() { ...

Ways to ensure CSS affects icon inside main element?

Struggling to match the background color of Material-UI icons with the rest of the list items on hover. The CSS is not applying to both the icon and text despite styling the overall class (className= "dd-content-item"). Any assistance would be greatly appr ...

Got a not-a-number (NaN) value for the `children` prop in a

Just starting out with React and working on a type racer app. I've encountered an issue while trying to calculate WPM (Words per minute) - the calculation keeps returning 'NaN'. I've double-checked all the variables and ensured there ar ...

Employing a "cross-domain" approach to serve as a login gateway for a different domain

I need to configure the domain: aaaa.com so that it can host a login form for the website located at domain: cccc.com. It's important to note that I have complete control over the server at cccc.com and have successfully set up CORS on that server. A ...

Ways to assign a value to an input element in AngularJS without impacting its ngModel

JAVASCRIPT: .directive('search', [function () { return { restrict: 'A', link: function (scope, element, attrs) { attrs.$set('placeholder', 'Word...'); console.log(attrs); ...

Alternative for Jquery: a new Hash Table solution using Prototype JS

Greetings everyone! I have experience as a prototype JS developer but now I am transitioning to jQuery for work/client reasons. One feature I really liked in Prototype was the Hash class, such as var h = new Hash();. However, I understand that jQuery doe ...

Utilizing dynamic jQuery events with variable integration

I'm having some trouble incorporating a variable into a dynamically added jQuery event. Every time I click, the message displayed is "The number is 3" for all div elements. $( document ).ready(function() { for (var i = 0; i < 3; i++) { ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

Trouble with HTML2PDF.js - download not being initiated

Currently, I am utilizing html2pdf.js in my project by following this tutorial: https://github.com/eKoopmans/html2pdf.js However, I've encountered an issue where despite implementing everything as instructed, the download prompt for the specified div ...

When utilizing Sequelize to insert data, PostgreSQL has the capability to return an additional table column

Encountered an error while attempting to add a new category: error: column "image" does not exist sql: 'INSERT INTO "Categories" ("id","createdAt","updatedAt") VALUES (DEFAULT,$1,$2) RETURNING " ...

Why is this <div> element refusing to budge according to my jQuery commands?

Currently embarking on a jQuery coding challenge where I am attempting to maneuver a circle around the page in a square pattern. Numerous methods have been tested with no success thus far. While I would like to showcase my various attempts, it would prove ...