Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify mongoose call lean().exec() throw is not a function #124

Closed
wants to merge 8 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion src/plugins/MongoosePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,42 @@ class MongoosePlugin implements SwPlugin {
if (!hasCB) {
if (ret && typeof ret.then === 'function') {
// generic Promise check
ret = wrapPromise(span, ret);

if (ret.constructor.name != 'Query') {
ret = wrapPromise(span, ret);
} else {
// Mongoose Query object
const chainMethods = ['select', 'sort', 'skip', 'limit', 'populate'];

// Mongoose Query object
const originalThen = ret.then;
const originalExec = ret.exec;
const originalLean = ret.lean;

// Preserve the query chain methods using arrow functions to maintain context
ret.then = (...args: any[]) => wrapPromise(span, originalThen.apply(ret, args));
ret.exec = (...args: any[]) => wrapPromise(span, originalExec.apply(ret, args));
ret.lean = (...args: any[]) => {
const leanQuery = originalLean.apply(ret, args);
// Preserve other chain methods on the lean result
leanQuery.then = ret.then;
leanQuery.exec = ret.exec;
return leanQuery;
};
// Wrap other common query methods that might be chained
chainMethods.forEach((method) => {
if (ret[method]) {
const originalMethod = ret[method];
ret[method] = (...args: any[]) => {
const result = originalMethod.apply(ret, args);
result.then = ret.then;
result.exec = ret.exec;
result.lean = ret.lean;
return result;
};
}
});
}
} else {
// no callback passed in and no Promise or Cursor returned, play it safe
span.stop();
Expand Down
Loading