'Delete by DATE object filter
In NodeJs, I need to delete records in MongoDB filtering by timezone (Date format).
In MongoDB, in a test record, I have:
"timestamp" : ISODate("2019-05-13T14:42:57.932+0000")
in the source code, I run the following query, passing a Date object as filter parameter for the delete command:
{timestamp: Mon May 13 2019 14:43:42 GMT+0200 (Central European Summer Time)}
If I write in string format the filter above (contained in the findParams parameter), I have the following:
JSON.stringify(findParams)
'{"timestamp":"2019-05-13T12:43:42.877Z"}'
The result is that the record is not deleted on the db. Where is the error?
Thanks.
UPDATE
Code used to delete records in MongoDB:
export async function deleteManyPromise(
collectionName: string,
findParams: Document,
proxy: MongoObject = _fbMarkMongoProxy
) {
const existsCollection = await checkCollectionExists(collectionName);
if (existsCollection) {
try {
if (!proxy.connectedDb) {
await proxy.connect();
}
const mongoDb = proxy.connectedDb;
const result = await mongoDb!
.collection(collectionName)
.deleteMany(findParams);
return result;
} catch (error) {
await closeAllDbConnections();
throw Error(`Error deleting collection ${collectionName} - ${error}`);
}
} else {
return;
}
}
Solution 1:[1]
Finally, the only solution that works for me to delete a record in MongoDB is to find a date by using the following filter (I start from a timestamp of type STRING; I have to search a timestamp of type DATE in MongoDB):
timestamp: new Date(record.timestamp + "Z")
and then, to insert a new record in MongoDB with timestamp of type DATE, starting from a timestamp of type STRING I have to write:
record.timestamp = new Date(new Date(record.timestamp + "Z").toISOString());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user1 |
