Skip to content

Bson upgrade #4

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

Bson upgrade #4

wants to merge 4 commits into from

Conversation

tee-tawk
Copy link

@tee-tawk tee-tawk commented Jun 17, 2025

Changes Made

Potential Risks

Test Plan

Checklist

  • I've increased test coverage
  • Since this is a public repository, I've checked I'm not publishing private data in the code, commit comments, or this PR.

Summary by CodeRabbit

  • New Features

    • Introduced a Mongoose plugin that adds pagination and search capabilities to Mongoose schemas, with customizable method names.
    • Exposed the new plugin for use in other parts of the application.
  • Dependency Updates

    • Upgraded bson and mongodb dependencies to newer versions.
    • Added mongoose as a new dependency.
  • Tests

    • Added comprehensive tests to verify the pagination and search features provided by the new Mongoose plugin.

Copy link

coderabbitai bot commented Jun 17, 2025

Walkthrough

This update introduces a new Mongoose plugin module that adds pagination and search static methods to Mongoose schemas. The package dependencies are updated, including the addition of Mongoose. The main export file is modified to export the new plugin, and a comprehensive test suite is added to verify the plugin's functionality.

Changes

File(s) Change Summary
package.json Updated bson and mongodb versions; added mongoose dependency; incremented package version.
src/index.js Added export for the new mongoosePlugin.
src/mongoose.plugin.js Introduced a Mongoose plugin adding static paginate and search methods to schemas.
test/mongoosePlugin.js Added tests for the Mongoose plugin, verifying pagination and search on models.
CHANGELOG.md Added changelog entry for version 1.0.1 documenting dependency updates and new mongoose plugin.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant MongooseModel
    participant PluginStaticMethod
    participant ExternalFindOrSearch

    App->>MongooseModel: Call paginate/search static method
    MongooseModel->>PluginStaticMethod: Invoke plugin method (paginate/search)
    PluginStaticMethod->>ExternalFindOrSearch: Call external find/search function
    ExternalFindOrSearch-->>PluginStaticMethod: Return results
    PluginStaticMethod-->>MongooseModel: Return results
    MongooseModel-->>App: Return paginated/search results
Loading

Poem

In the garden of code, new features bloom bright,
With Mongoose now hopping in, everything feels right.
Paginate and search, with methods so keen,
Tests run like rabbits, swift and unseen.
Version hops up, dependencies in tow—
Our codebase grows stronger, row by row!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4bb6dcf and ef29677.

📒 Files selected for processing (1)
  • CHANGELOG.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@tee-tawk tee-tawk self-assigned this Jun 17, 2025
@tee-tawk tee-tawk requested a review from pyhrus June 17, 2025 04:09
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
src/mongoose.plugin.js (1)

43-53: Avoid silently overriding existing statics

Before assigning schema.statics[name] / searchFnName, check whether a static with that key already exists; otherwise consumers may unknowingly lose previous behaviour.

if (schema.statics[name]) {
  throw new Error(`Static "${name}" already exists on schema`);
}
schema.statics[name] = findFn;
src/index.js (1)

6-15: Document the new public surface

mongoosePlugin is now part of the public API but README / JSDoc were not updated. Exposing it without docs makes adoption harder.

At minimum, add a usage snippet:

const { mongoosePlugin } = require('@tawk.to/mongo-cursor-pagination');
MySchema.plugin(mongoosePlugin);
test/mongoosePlugin.js (2)

56-58: Release DB connections to prevent Jest open-handle leaks

The test disconnects the in-memory server but keeps the Mongoose connection open, which can cause “Jest did not exit one second after the test run” warnings on some CI environments.

 afterAll(async () => {
+  await mongoose.disconnect();
   await mongod.stop();
 });

51-54: ensureIndexes is deprecated in Mongoose 7

Use Model.createIndexes() or Model.syncIndexes() to avoid deprecation warnings and future breakage.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d814403 and 4bb6dcf.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • package.json (3 hunks)
  • src/index.js (1 hunks)
  • src/mongoose.plugin.js (1 hunks)
  • test/mongoosePlugin.js (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/mongoose.plugin.js (3)
src/index.js (3)
  • find (3-3)
  • require (5-5)
  • search (4-4)
src/find.js (2)
  • require (5-9)
  • _ (1-1)
src/search.js (1)
  • _ (1-1)
🪛 Biome (1.9.4)
src/mongoose.plugin.js

[error] 43-43: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 49-49: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (1)
package.json (1)

38-42: ```shell
#!/bin/bash
set -e

echo "=== Checking [email protected] engines requirement ==="
if command -v npm >/dev/null 2>&1; then
npm view [email protected] engines --json
else
curl -s https://registry.npmjs.org/mongoose/7.0.5 | jq '.engines'
fi

echo
echo "=== Checking [email protected] engines requirement ==="
if command -v npm >/dev/null 2>&1; then
npm view [email protected] engines --json
else
curl -s https://registry.npmjs.org/bson/6.7.0 | jq '.engines'
fi


</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment on lines +40 to 42
"bson": "^6.7.0",
"mongoose": "^7.0.5",
"object-path": "^0.11.5",
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider pinning major versions or adding an integration test

bson, mongodb and the new mongoose dependencies are all major-version jumps. If any public helpers still rely on an older driver API (e.g. ObjectId helpers, cursor methods) they may break silently.

If full semantic-version tolerance is intended, add integration tests against the new driver; otherwise pin the exact major you have verified.

Also applies to: 59-59

🤖 Prompt for AI Agents
In package.json around lines 40 to 42 and line 59, the dependencies bson,
mongodb, and mongoose have been updated with major version changes which may
cause silent breaks if older driver APIs are still used. To fix this, either pin
these dependencies to the exact major versions you have tested to ensure
compatibility or add integration tests that verify all public helper functions
work correctly with the new driver versions to catch any breaking changes early.

Comment on lines +13 to +41
module.exports = function (schema, options) {
/**
* paginate function
* @param {Object} params required parameter
*/
const findFn = function (params) {
if (!this.collection) {
throw new Error('collection property not found');
}

params = _.extend({}, params);

return find(this.collection, params);
};

/**
* search function
* @param {String} searchString String to search on. Required parameter
* @param {Object} params
*/
const searchFn = function (searchString, params) {
if (!this.collection) {
throw new Error('collection property not found');
}

params = _.extend({}, params);

return search(this.collection, searchString, params);
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Provide safer defaults & parameter validation

Small hardening tweaks:

  1. Default the options object to avoid repeated null-checks and reduce cognitive load.
  2. Validate searchString to prevent accidental calls with undefined, which can yield confusing results downstream.
  3. Use object spread instead of _.extend to remove the underscore dependency inside hot paths.
-module.exports = function (schema, options) {
+module.exports = function (schema, {
+  name = 'paginate',
+  searchFnName = 'search'
+} = {}) {
   /**
    * paginate function
    * @param {Object} params required parameter
    */
-  const findFn = function (params) {
+  const findFn = function (params = {}) {
     if (!this.collection) {
       throw new Error('collection property not found');
     }
-    params = _.extend({}, params);
-    return find(this.collection, params);
+    return find(this.collection, { ...params });
   };
@@
-  const searchFn = function (searchString, params) {
+  const searchFn = function (searchString, params = {}) {
     if (!this.collection) {
       throw new Error('collection property not found');
     }
-
-    params = _.extend({}, params);
-
-    return search(this.collection, searchString, params);
+    if (typeof searchString !== 'string' || !searchString.length) {
+      throw new TypeError('searchString must be a non-empty string');
+    }
+    return search(this.collection, searchString, { ...params });
   };
-
-  if (options && options.name) {
-    schema.statics[options.name] = findFn;
-  } else {
-    schema.statics.paginate = findFn;
-  }
-
-  if (options && options.searchFnName) {
-    schema.statics[options.searchFnName] = searchFn;
-  } else {
-    schema.statics.search = searchFn;
-  }
+  schema.statics[name] = findFn;
+  schema.statics[searchFnName] = searchFn;
 };

This removes the optional-chaining lint warnings, tightens typing, and trims dependencies.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
module.exports = function (schema, options) {
/**
* paginate function
* @param {Object} params required parameter
*/
const findFn = function (params) {
if (!this.collection) {
throw new Error('collection property not found');
}
params = _.extend({}, params);
return find(this.collection, params);
};
/**
* search function
* @param {String} searchString String to search on. Required parameter
* @param {Object} params
*/
const searchFn = function (searchString, params) {
if (!this.collection) {
throw new Error('collection property not found');
}
params = _.extend({}, params);
return search(this.collection, searchString, params);
};
module.exports = function (schema, {
name = 'paginate',
searchFnName = 'search'
} = {}) {
/**
* paginate function
* @param {Object} params required parameter
*/
const findFn = function (params = {}) {
if (!this.collection) {
throw new Error('collection property not found');
}
return find(this.collection, { ...params });
};
/**
* search function
* @param {String} searchString String to search on. Required parameter
* @param {Object} params
*/
const searchFn = function (searchString, params = {}) {
if (!this.collection) {
throw new Error('collection property not found');
}
if (typeof searchString !== 'string' || !searchString.length) {
throw new TypeError('searchString must be a non-empty string');
}
return search(this.collection, searchString, { ...params });
};
schema.statics[name] = findFn;
schema.statics[searchFnName] = searchFn;
};
🤖 Prompt for AI Agents
In src/mongoose.plugin.js around lines 13 to 41, improve safety by defaulting
the options parameter to an empty object to avoid null checks, add validation to
ensure searchString is defined before proceeding in searchFn, and replace
_.extend calls with object spread syntax to eliminate the underscore dependency
and simplify the code.

Comment on lines +70 to +77
it('returns data in the expected format', async () => {
const data = await Post.paginate();
expect(hasOwnProperty.call(data, 'results')).toBe(true);
expect(hasOwnProperty.call(data, 'previous')).toBe(true);
expect(hasOwnProperty.call(data, 'hasPrevious')).toBe(true);
expect(hasOwnProperty.call(data, 'next')).toBe(true);
expect(hasOwnProperty.call(data, 'hasNext')).toBe(true);
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Use a stable property-check helper

hasOwnProperty is not guaranteed to be in scope inside CommonJS modules and will throw in strict mode. Guard with Object.prototype.hasOwnProperty.call.

-expect(hasOwnProperty.call(data, 'results')).toBe(true);
+expect(Object.prototype.hasOwnProperty.call(data, 'results')).toBe(true);

Apply to the other assertions as well.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('returns data in the expected format', async () => {
const data = await Post.paginate();
expect(hasOwnProperty.call(data, 'results')).toBe(true);
expect(hasOwnProperty.call(data, 'previous')).toBe(true);
expect(hasOwnProperty.call(data, 'hasPrevious')).toBe(true);
expect(hasOwnProperty.call(data, 'next')).toBe(true);
expect(hasOwnProperty.call(data, 'hasNext')).toBe(true);
});
it('returns data in the expected format', async () => {
const data = await Post.paginate();
- expect(hasOwnProperty.call(data, 'results')).toBe(true);
+ expect(Object.prototype.hasOwnProperty.call(data, 'results')).toBe(true);
expect(hasOwnProperty.call(data, 'previous')).toBe(true);
expect(hasOwnProperty.call(data, 'hasPrevious')).toBe(true);
expect(hasOwnProperty.call(data, 'next')).toBe(true);
expect(hasOwnProperty.call(data, 'hasNext')).toBe(true);
});
🤖 Prompt for AI Agents
In test/mongoosePlugin.js around lines 70 to 77, the code uses
hasOwnProperty.call directly, which may not be stable or available in strict
mode. Replace all instances of hasOwnProperty.call with
Object.prototype.hasOwnProperty.call to ensure the property check is reliable
and does not throw errors. Update all assertions in this test block accordingly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants