Get stack trace from errors using mongoose without calling .exec()?

Viewed 209

I recently read in the mongoose docs that to get a stack trace from mongoose errors that includes details about which file the mongoose code was called from, you need to call .exec()?

Example:

I currently have a lot of code using this structure:

await collection.deleteMany({});

Do I need to add .exec() to get a more helpful stack trace?

await collection.deleteMany({}).exec();

If so, is there a global workaround, so I don't have to add .exec() a countless number of times?

References:

https://mongoosejs.com/docs/promises.html#should-you-use-exec-with-await https://github.com/Automattic/mongoose/issues/8747

1 Answers

No, you can't get proper stack traces with await without using .exec().

This is elaborated on in another issue referenced in the GitHub issue you linked:

await Model.findOne() without exec() will unfortunately remove the calling file from the stack trace because of how V8's await handles custom thenables.

You can also see this in the source for Query.prototype.then, which calls exec() under the hood, then calls .then() on its result, which prevents JavaScript from tracing the error back to your code.

As a result, there is no workaround for this, and you will need to either migrate your codebase to using exec(), or hope the Node.js engine is improved to better handle this at some point.

Related