I’ve setup the plugin cypress-mongodb
for Cypress according to the documentation, and I think everything should work, because I am able to successfully use
cy.deleteMany({},{collection: 'colname', database: 'dbname'})
to clear the collection, but I have problem with adding documents back.
Here is a sample code I try to insert:
cy.insertOne({
_id: "3c329243-3ff2-4c11-af09-a51ba33f9a18",
application: {
lt: "A",
someDate: {
$date: "2023-09-19T00:00:00.000Z"
},
otherDate: {
$date: "2023-09-13T00:00:00.000Z"
}
},
ids: [],
createdAt: {
$date: "2023-09-13T10:56:16.000Z"
}
}, {collection: 'colname', database: 'dbname'})
but fail with:
> Document failed validation Learn more
node_modules/cypress-mongodb/dist/commands/insert.js:22:1
20 | }
21 | args.document = (0, bson_1.serialize)(args.document);
> 22 | return cy.task('insertOne', args).then(function (result) {
| ^
23 | return result;
24 | });
25 | }
This document above is just an example, but when I try to add the same real document through MongoDB Compass it validates, and gets added without problems.
We use MongoDB 5.0.13 Community
Does anyone know what could be wrong?
2
Answers
Okay, I have found the problem and the solution.
Since we use MongoDB the documents are saved as Extended JSON (EJSON) with specified field data types that are somewhat incompatible with JS format.
The reason I was getting the error was DB side validation error due to sending JS object with EJSON structure:
Now, to correctly change the EJSON document (or array of docs) into JS object I had to use bson npm package and it's
EJSON.deserialize()
method like this:There seems to be an update to the library in the code mentioned in the error message.
Compare your error message to the latest source
You may find it goes away if you bring your install up to the latest version.
Or at least get some more helpful error diagnostics.