A comprehensive guide on extracting matching date from MongoDB with Mongoose

I'm currently facing an issue with returning the appropriate records for a given date query in MongoDB and Mongoose. Despite my efforts, all rows are being returned instead.

Below, you'll find the relevant code snippet as well as the model schema. Please note that the "todaydate" field is of type Date.

MongoDB Data:

{ 
_id:ObjectId("5edd1df67b272e2d4cf36f70"),
pname:"Test 1",
category:"Choco 1",
todaydate:2020-06-01T18:30:00.000+00:00
},
{ 
_id:ObjectId("5gdd1df67b272e2d4cf36f72"),
pname:"Test 2", 
category:"Choco 3",
todaydate: 2020-06-02T18:30:00.000+00:00
},
{ 
_id:ObjectId("5kdd1df67b272e2d4cf36f74"),
pname:"Test 5", 
category:"Choco 6",
todaydate: 2020-05-01T18:30:00.000+00:00
},
{ 
_id:ObjectId("5ewd1df67b272e2d4cf36f75"),
pname:"Test 6", 
category:"Choco 8",
todaydate: 2020-06-03T18:30:00.000+00:00
} 

data.model.js:

const mongoose = require('mongoose'); 
var userSchemaDate = new mongoose.Schema({ 
    pname: {
        type: String
    },  
    category: {
        type: String
    },  
    todaydate: {
        type: Date
    }   
}, {
    versionKey: false,
    collection: 'data'
}); 

module.exports = mongoose.model('Data', userSchemaDate);

data.controller.js:

module.exports.getReportTableData = (req, res, next) => {
    var collection = req.query.collection;  
    let tabledata = dbc.model(collection);  
    let reportPar = new Date("2020-06-03"); //yyyy-mm-dd
        tabledata.find({
            todaydate: {
                $gte: reportPar
            }
        }, function(err, docs) {
            if (err) {
                console.log(err);
                return;
            } else {
                console.log("Successfully loaded data");
                res.json({ data: docs, msg: 'Data loaded.' });
            }
        }); 
     }

Answer №1

Upon examining your example, I couldn't identify any issues that appear to be problematic, assuming the synchronization of your system clocks is accurate.

Here's a code snippet provided for comparison purposes:

mongoose.connect(`mongodb://localhost/tests`, {useNewUrlParser: true, useUnifiedTopology: true, autoIndex: false});
const db = mongoose.connection;

db.on('error', (err) => {
    console.error(err);
});

db.once('open', async () => {
    // Clear the table
    const collections = await db.db.collections();
    if (collections.map(c => c.s.namespace.collection).includes('datetests')) {
        await db.db.collection('datetests').drop();
    }

    // Define schema
    const schema = new Schema(
        {
            todaydate: {
                type: Date,
                required: true
            }
        },
        {
            versionKey: false,
            timestamps: false
        }
    );

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

    // Insert dates for a week
    let start = new Date('2020-06-02');
    for(let i = 0; i < 7; i++) {
        const date = new Date(start.valueOf());
        date.setDate(start.getDate() + i);

        await Test.create({
            todaydate: date
        });
    }

    let result = await Test.find({
        todaydate: {
            $gte: new Date('2020-06-02'), $lte: new Date('2020-06-02')
        }
    }).exec();

    assert.ok(result.length === 1);

    result = await Test.find({
        todaydate: {
            $gte: new Date('2020-06-02'), $lte: new Date('2020-06-03')
        }
    }).exec();

    assert.ok(result.length === 2);

    result = await Test.find({
        todaydate: {
            $gte: new Date('2020-06-02'), $lte: new Date('2020-06-05')
        }
    }).exec();

    assert.ok(result.length === 4);

    result = await Test.find({
        todaydate: {
            $gte: new Date('2020-06-02'), $lte: new Date('2020-06-08')
        }
    }).exec();

    assert.ok(result.length === 7);
});

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

Is there a Nuxt/Vue glitch causing the server to be called multiple times on a single route or page?

Why is Nuxt making multiple server calls on a single route/page? I tested the example from their express-template: import express from 'express' import { Nuxt, Builder } from 'nuxt' import api from './api' const app = expr ...

The response from the nodejs request.body function is showing an empty object as

I have implemented the code below, but when I use request.body it returns an empty object {}. Ideally, I would like to see my output as {username:"Mani",password:"pass"}. Can someone help me identify any issues in this code snippet? app.js var bodyParser ...

Yaml file validation encountered an issue with Swagger specifications

I am working with a swagger yaml specification that looks like this: swagger: "2.0" info: version: "0.0.1" title: Chat API # during dev, should point to your local machine host: localhost:5000 # basePath prefixes all resource paths basePath: /api/v2 ...

The outcome of AES encryption varies when comparing Node JS with C# programming languages

In a particular scenario, I need to encrypt and transmit text using the AES 256 algorithm. The decryption process will be handled by client-side C# code. Here is the encryption code in JavaScript: const crypto = require('crypto'); algorithm = ...

Retrieving CSS style values with Node.js

I am looking to design a new CSS style that includes the lowest and highest values. table[my-type="myStyle"] { width: 255.388px !important; } This code snippet is included in numerous CSS files within my style directory. ...

The Express server automatically shuts down following the completion of 5 GET requests

The functionality of this code is as expected, however, after the fifth GET request, it successfully executes the backend operation (storing data in the database) but does not log anything on the server and there are no frontend changes (ReactJS). const ex ...

What is the reason for not opening the ndb debugger in the package.json file?

Here is my package.json file: { ... "scripts": { "start": "nodemon server.js", "start:prod": "NODE_ENV=production nodemon server.js", "debug": "ndb server.js" }, ... The npm command ndb has been made global. However, when I run npm run d ...

I'm trying to figure out which one is the correct term on Ubuntu - is it "node" or "nodejs"? And

Trying to install webpack-dev-server but it requires the latest version of nodejs. I am using Ubuntu 20.04 and attempted to update with nvm, which did not work. Following this Q&A answer here, I then tried to install nodejs using sudo apt-get install ...

Ways to resolve the issue "Module Not Found Error: Cannot locate module './src/bot/index'"

Whenever I run the command node src/index.js I encounter the following error message: Error: Cannot find module './src/bot/index' Require stack: C:\Users\MIMAR\Desktop\EJS\src\index.js What could be causing this er ...

What could be causing the array value at index[i] within the for loop to be undefined?

As a beginner in nodeJs, I am facing an issue with the array[i] value turning undefined after fetching data from a specific URL within a for loop. I'm struggling to find a solution to this problem. Any assistance would be greatly appreciated. Below i ...

Tips for transferring a file to PocketBase using NodeJs

Currently, I am in the midst of a project that necessitates uploading numerous PDF files to a PocketBase collection. All the necessary files are saved on my computer and my goal is to upload them using nodejs along with the PocketBase JavaScript SDK. Howe ...

What is the proper way to specifically define a new property on the `global` object in TypeScript?

I want to define a type signature for the variable below: (global as any).State = { variables: {}, }; How can I declare the type of State? If I try (global as any).State: Something = ..., the compiler displays an error message saying ; expected. It se ...

MongoDB virtual fields failing to populate in Mongoose

User Model const mongoose = require("mongoose"); const validator = require("validator"); const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const Task = require("./tasks"); const user ...

Using Socket.IO in Node.js to distribute information to every connected client

Currently, I am in the process of developing a WebGL multiplayer game. My approach involves using socket.io and express in node.js to enable multiplayer functionality. However, I am encountering an issue with broadcasting key events. When a user presses a ...

Error messages encountered following the latest update to the subsequent project

Recently, I upgraded a Next project from version 12 to 14, and now I'm encountering numerous import errors when attempting to run the project locally. There are too many errors to list completely, but here are a few examples: Import trace for requeste ...

Is there a way to retrieve just the array element as the output instead of the entire object in MongoDB?

Here is the code snippet I am using to display review array data from the restaurant collection object: async get(reviewId) { const restaurantsCollection = await restaurants(); reviewId = ObjectId(reviewId) const r = await restaurantsCollect ...

Need to install Node.js in order to install n and then install Node.js again?

I'm struggling to understand how to use n. It seems that it is a version manager for Node.js similar to nvm. Unlike nvm, which is essentially a shell script, the documentation advises using npm to install n: $ npm install -g n What confuses me is t ...

Auto-refresh the page upon any updates made to the MongoDB collection

I'm currently working on a Node.Js project that involves MongoDB integration. I'm looking for a way to automatically refresh one of my HBS pages whenever there is a change in my MongoDB collection. I could use some guidance on the best approach ...

Modify entry if present, otherwise insert in a node/express application

After developing a Restful API with Node/Express and Mongo, I encountered a challenge. I have to implement an endpoint to either update the existing record of a user if their email address is found or create a new record if it is not. Uncertain about the ...

Managing JSON data retrieval and manipulation with REST API in Node.js and MongoDB

My technology stack includes Node.js and MongoDB with a rest api. The input data I'm dealing with looks like this: var doc={"name":"ABX", duedate : new Date() } Before sending it to the server, I stringify the data: /rest/update?doc=JSON.s ...