I call collection.find(someBadQuery) and I get an error from MongoDB. But it ends up as unhandled rejection. How to handle this rejection?
As described in docs For find() MongoDB NodeJS driver returns FindCursor and not promise, therefore .catch(), or async try ... catch will not work. It is EventEmmiter, but there is no error event.
Is there any way how to track which .find() call caused the error?
The error is for example:
Unhandled rejection: MongoServerError: E11000 duplicate key error collection: data.Users__UserRole index: title_1 dup key: { title: null }
at ...\node_modules\mongodb\lib\operations\insert.js:53:33
at ...\node_modules\mongodb\lib\cmap\connection_pool.js:277:25
at ...
at handleOperationResult (...\node_modules\mongodb\lib\sdam\server.js:335:20)
at Connection.onMessage (...\node_modules\mongodb\lib\cmap\connection.js:222:9)
at MessageStream.<anonymous> (...\node_modules\mongodb\lib\cmap\connection.js:63:60)
at MessageStream.emit (node:events:513:28)
at processIncomingData (...\node_modules\mongodb\lib\cmap\message_stream.js:132:20)
at MessageStream._write (...\node_modules\mongodb\lib\cmap\message_stream.js:33:9)
at writeOrBuffer (node:internal/streams/writable:391:12)
at _write (node:internal/streams/writable:332:10)
at MessageStream.Writable.write (node:internal/streams/writable:336:10)
at Socket.ondata (node:internal/streams/readable:754:22)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23)
at TCP.callbackTrampoline (node:internal/async_hooks:130:17) {
So how can I prevent unhandled rejections and actually trace query which causes the error? Where should I put error handler? Thanks.
findinitiates the search request, driver retrieves the data, andcursormakes it available on application level. What was the error?process.on('uncaughtException', handler)but there is little you can do at this point but exit the process. I