Unable to convert string from BSON format to Date object

I am facing an issue with the data stored in my mongoDB collection (data_extraction_test). Here is an example of the data:

{
    "_id" : ObjectId("4f16fc97d1e2d32371003e27"),
    "date" : "14 Nov 2000 08:22:00 -0800"
}

{
    "_id" : ObjectId("4f16fc97d1e2d32371003e28"),
    "date" : "14 Nov 2000 07:37:00 -0800"
}

{
    "_id" : ObjectId("4f16fc97d1e2d32371003e29"),
    "date" : "14 Nov 2000 07:25:00 -0800"
}

Upon running the provided javascript code for extraction, an error occurs stating: Can't convert from BSON type string to Date.

let cursor = col.aggregate([
                        {
                            $project:{
                                _id: "$_id",
                                year: {$year: new Date("13 Nov 2000 01:41:00 -0800 (PST)")},
                                // month: new Date(new String("$date")),
                                month: { $month: "$date" },
                            }
                        },
                        {
                            $out: "dan"
                        }
                    ]).toArray((err, items)=>{
                        assert.equal(null, err);
                        console.log("daniel",items);
                        resolve(true);
                        db.close();
                    });

I need assistance on how to successfully convert the string into ISODate format.

Answer №1

The issue arises from attempting to convert RFC date format as a string object, while the query expects it to be a Date object.

To resolve this, I converted the dates in your database to ISO 8601 format:

"14 Nov 2000 08:22:00 -0800" => ISODate("2000-11-14T16:22:00.000Z")

"14 Nov 2000 07:37:00 -0800" => ISODate("2000-11-14T15:37:00Z")

"14 Nov 2000 07:25:00 -0800" => ISODate("2000-11-14T15:25:00Z")

Following this update, the aggregation query successfully executed.

It is worth noting that according to the documentation, dates are stored as a 64-bit integer representing milliseconds since the Unix epoch (Jan 1, 1970).

Consider storing dates as Date objects instead of strings initially. Is there a specific reason for storing them as strings?

Update: As suggested by user Neil Lunn in the provided link, you can use the following script to convert the property to ISO date:

(Please backup your database before proceeding)

//change test to your collection name 
db.test.find({}).forEach(function (doc) {
    doc.date = new Date(doc.date);
    db.test.save(doc);
});

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

Tips for effectively utilizing generics in typescript

Having trouble understanding how to properly utilize generics. Can someone help me use generics in the following scenario: export interface Location { id: number; address: { houseNumber: string; }; } export const getEuropeLocations = async ( ap ...

Guide to passing parameters in the pop method of Ionic 2

When using the push method in Ionic2, I attempted to pass parameters like so: this.nav.push(SecondPage, { thing1: data1, thing2: data2 }); However, I'm curious if there is a way to pass parameters in the pop() method. ...

Why do we need the TypeScript ts-jest pre-processor?

I am relatively new to TypeScript and JavaScript, so I have a question regarding the necessity of preprocessing modules like ts-jest for running Jest tests with TypeScript code. Currently, I am working on a TypeScript project in Node and everything seems t ...

What could be causing this RangeError to constantly come up while I'm performing a basic math operation in node.js?

My program simply takes two inputs from an HTML form, parses them into text in Node, and then performs a math operation on the two. Strangely, this issue only occurs when dealing with numbers, not strings. Despite the error message indicating an invalid s ...

There was no timeout triggered on the second attempt to retrieve data

I have implemented a login page in React-Native that functions properly when there is an Internet connection. However, I now need to address the scenario where the Internet or server connection is unavailable. My approach to handling this is by utilizing t ...

What is the meaning of a word character in a character class?

\w - represents the character class [A-Za-z0-9_] Character class Despite this, I find it difficult to grasp how it is interpreted within a character class. When I use [\w-~] let test = (str) => /^[\w-~]+$/.test(str) console.log(tes ...

retrieve results upon expiry of time limit

What is the best way to retrieve a value after a timeout in the following function? $fetch: function($timeout) { var breadCrumbs; info = []; $timeout(function() { info = getCrumbs(); console.log(info); ...

Unable to showcase information in the center of an HTML document

Hello, I'm facing an issue with my HTML page that has a left vertical nav-bar. Despite my efforts, I can't seem to display content (text) in the center of the page as shown in the screenshot with the red oval. I've attempted inserting text ...

Angular4 is throwing the error "TypeError: Cannot access the '_id' property of an undefined value."

My mean stack application is up and running smoothly, with CRUD functionalities in place. The backend functions correctly by posting data to MongoDB. However, I am facing an issue on the front end that displays the following error: ERROR Type Error: C ...

What is the best way to adjust the width of floating divs to completely fill the space they occupy?

On the first picture, there are six equal divs displayed. As the screen size increases, the width of the divs also grows to fill up their space, like a table cell or another div. If there is enough space in the first row to accommodate the fourth div, it s ...

error": "message": "Property 'name' cannot be read because it is undefined

I've encountered an issue while creating a route to handle POST data. Despite testing it on postman, I have not been able to find a solution for the problem that many others seem to be facing as well. It seems like the 'name' field is not be ...

techniques for tracking instance variables in a Ruby controller and transferring them to an HTML view utilizing AJAX

Hello, I am looking to create a page that dynamically monitors or renders the value of a variable within the controller as it iterates through different values. view.html.erb <a id='get_value' class="btn">Run</a> <ul id="value_va ...

Unable to locate or modify an item within an array

I have a unique way of organizing my collection, with an array inside. Here's how it looks: const postsSchema = mongoose.Schema({ posts: {type: Array}, }) Now, I want to search for a specific document within this collection. I attempted the follo ...

Can anyone assist me with form validation in JavaScript and jQuery?

There seems to be an issue with the query in this scenario. When I input a correct email address into the email box, it successfully validates it. However, if I then change the email box to be empty, it still displays the previously entered correct email ...

Creating a visual representation from tabular data: A step-by-step guide

Hello there! I appreciate any assistance you can provide! Could you guide me on creating a script (using PHP or JavaScript) that functions as a chart constructor? The input values should be data retrieved from a database table and displayed on the web pa ...

When you download a file through the unpkg CDN, the size of the npm package is

I am experiencing a discrepancy with the file size of a file in my npm package. The file is 307kb in size, but when I download it through unpkg, the same file is only 73.2Kb. I find it quite puzzling how the file can be smaller when downloaded over the net ...

The Interactive Menu Toggler: A jQuery Solution

$(window).on('resize', function() { if ( $( window ).width() > 768 ) { $('#menu-main-navigation').show(); } }); $('#nav-toggle').on('click', function() { // start of the nav toggle $('#m ...

Tips on obtaining the response (in JSON format) in your console when accessing a URL

Can someone help me integrate this code into my project and guide me on how to proceed with it? function validate() { var un = document.loginscreen.uname.value; var pw = document.loginscreen.psw.value; var username = "John_Smith"; var passw ...

Ways to modify the color of cells in a table generated from JSON

In developing an HTML table based on JSON data, I have created a university semester map that displays student information including their ID, year, term, and required courses for graduation. While the table is successfully created, I aim to customize the ...

Is there a way to verify that all of my HTML elements have been loaded in AngularJS?

I am currently utilizing angularJS version 1.2.1 along with angular-ui-bootstrap. Within my code, I have a collection of <ng-includes> tags from angularjs and <accordion> components from angular-ui. When loading the content, I need to initiat ...