typegoose / mongodb-memory-server

Manage & spin up mongodb server binaries with zero(or slight) configuration for tests.
https://typegoose.github.io/mongodb-memory-server/
MIT License
2.58k stars 187 forks source link

Timestamp saving should be ISODate #721

Closed natlibfi-jonollil closed 1 year ago

natlibfi-jonollil commented 1 year ago

Versions

package: mongo-memory-server

What is the Problem?

When Inserting dates to database it saves those in wrong type. https://www.mongodb.com/docs/manual/reference/method/Date/ When i log same data from real mongo it shows as this:

"creationTime" : ISODate("2022-12-01T07:38:16.512Z")

Code Example

  const connectionUri = await mongoFixtures.getUri();
  const client = await MongoClient.connect(connectionUri, {useNewUrlParser: true});
  await client.db().collection('test').insertOne({creationTime: new Date('2000-01-01T00:00:01.000Z')});
  const data = await client.db().collection('test').findOne();
  console.log(data);

Debug Output

Debug Output ```txt "creationTime": [Date: 2022-05-01T00:00:01.000Z] ```

Do you know why it happenes?

no (I suspect that mongo-memory-server does not save date objects in right format)

natlibfi-jonollil commented 1 year ago

I noticed problem when i had to look for items between certain time period, here is simplified example:

client.db().collection('test').findOne({creationTime: {$lte: new Date(), $gte: new Date('1900-01-01T00:00:01.000Z')}})

Real Mongodb handles this ok but mongo-memory-server does not

hasezoey commented 1 year ago

cannot reproduce, code used:

// NodeJS: 18.10.0
// MongoDB: 5.0 (Docker)
// Typescript 4.8.4
import { MongoClient } from 'mongodb';
import { MongoMemoryServer } from 'mongodb-memory-server';

(async () => {
  const server = await MongoMemoryServer.create();
  const uri = server.getUri();
  const client = await MongoClient.connect(/* 'mongodb://localhost:27017/' */ uri);
  await client
    .db()
    .collection('test')
    .insertOne({ creationTime: new Date('2000-01-01T00:00:01.000Z') });
  const data = await client.db().collection('test').findOne();
  console.log((data as any).creationTime instanceof Date); // true
  console.log(data);

  await client.close();
  await server.stop();
})();

to test with a local instance (in my case with docker) just comment out uri and uncomment the localhost string


keep in mind that MMS only downloads and manages the binary process, it does not change anything with the connection itself - it is still like if you would start a manual binary or use a docker mongodb image

also note that printing of values may differ from the mongoshell (or compass) with what the mongodb nodejs driver shows (or mongoose), in the nodejs driver a ISODate will just be a native js Date, the mongodb driver will transparently translate


PS: closing because this is not a MMS issue, you can still ask if you have questions