Using EJSON in NodeJS

Using the native Mongdb Node.js driver (3.6.6) and am trying to work with date.

I’m having issues with dates. All my calls to the DB seem to use standard JSON and not EJSON. For example, the following object for import fails. {“EventDate”: {"$date":“2021-05-03T23:24:00.000Z”}}

Also, when data is returned, the format is standard JSON. Is there some way to enable or use EJSON in the driver?

Hello @Cory_Engel, welcome to the MongoDB Community forum!

… the following object for import fails. {“EventDate”: {“$date”:“2021-05-03T23:24:00.000Z”}}

I tried the following procedure to import the above data using mongoimport.

The JSON file content: {"EventDate": {"$date":"2021-05-03T23:24:00.000Z"}}

The date data representation {"$date":"2021-05-03T23:24:00.000Z"} is Extended JSON.

Import:

mongoimport --db=test --collection=json_coll --file=inp-json.json

Queried from mongo shell:

{ "_id" : ObjectId("60a334a8c568b2172d52e65d"), "EventDate" : ISODate("2021-05-03T23:24:00Z") }

The import is successful and the created document is fine too.

MongoDB stores data as BSON types, and there is a Date type too.

Thanks. I’m able to do that too, and also using Compass or the shell. But the issue is via the Mongodb driver for node.js. When I try it via the driver, it fails.

Hello @Cory_Engel, please share the code you had tried.

Here is the relevant snippet. In the failing case, req.body = {“EventDate”: {"$date":“2021-05-03T23:24:00.000Z”}}

Thanks for your assistance!

exports.create = async (req, res) => {
  try {
    console.log(req.body);
    const Result = await db
      .getDb()
      .db()
      .collection(req.params.collection)
      .insertOne(req.body);
    res.status(201).json({
      status: 'Success',
      data: {
        entry: Result
      }
    });
  } catch (err) {
    res.status(404).json({
      status: 'Failed',
      message: err
    });
  }
};

Hello @Cory_Engel,

I tried to insert the document using NodeJS driver v3.6.3 and MongoDB v4.2.8 - as you had mentioned it fails with an error: Error: key $date must not start with '$'

But, I could insert the same document via mongo shell. There is a rule that only top-level fields with names starting with a $ cannot be inserted (see Documents - Field Names). In the shell, the following first document fails, but the second gets inserted.

{ $fld: "some value" }
{ fld: { $sub-fld: "some value" } }

But, with NodeJS Driver code, both the inserts fail.

I saw this post on Stack Overflow with some similar discussion: How to Insert records into mongo with Node where records have an $oid .