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

fix(collection): avoid buffering if creating a collection during a connection interruption #15187

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

vkarpov15
Copy link
Collaborator

Summary

Should be a fix for #14971.

In Mongoose 7+8, buffering should only happen before mongoose.connect() has been called. The reason why Mongoose still has buffering is that the MongoDB node driver will error out if you try to send a database operation on a MongoClient instance that you haven't called connect() on yet. But once the MongoDB Node driver has connected successfully to MongoDB at least once, database operations like find() etc. handle retries and disconnection via an internal server selection process, so Mongoose buffering is unnecessary.

When investigating #14971, I found that Mongoose may still buffer if the collection is created during a connection interruption. For example, in the following script, console.log('Buffer', TestModel.collection.buffer); will print "Buffer true" if you shut down the MongoDB server on 127.0.0.1:27017 when "Waiting 5 seconds, shut down the MongoDB server now" prints

'use strict';

const mongoose = require('mongoose');

(async function main() {
  await mongoose.connect('mongodb://127.0.0.1:27017/mongoose_test');

  console.log('Waiting 5 seconds, shut down the MongoDB server now');
  await new Promise(resolve => setTimeout(resolve, 5000));

  console.log('Executing find...');
  const TestModel = mongoose.model('Test', mongoose.Schema({ name: String }));
  console.log('Buffer', TestModel.collection.buffer);
  const promise = TestModel.find().exec();


  console.log(await promise);
  console.log('Done');
})();   

With this fix, buffering will not kick in, the above script will print "Buffer false". Which should prevent unintended buffering in the future.

_hasOpened is a property that Mongoose sets on the connection the first time the connection's readyState is set to 1 (connected)

In the interest of being cautious, I'm putting this and #14971 in the 8.10 milestone.

Examples

@vkarpov15 vkarpov15 added this to the 8.10 milestone Jan 17, 2025
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.

1 participant