File tree 2 files changed +26
-17
lines changed 2 files changed +26
-17
lines changed Original file line number Diff line number Diff line change @@ -818,32 +818,41 @@ Connection.prototype.dropCollection = async function dropCollection(collection)
818
818
/**
819
819
* Waits for connection to be established, so the connection has a `client`
820
820
*
821
+ * @param {Boolean } [noTimeout=false] if set, don't put a timeout on the operation. Used internally so `mongoose.model()` doesn't leave open handles.
821
822
* @return Promise
822
823
* @api private
823
824
*/
824
825
825
- Connection . prototype . _waitForConnect = async function _waitForConnect ( ) {
826
+ Connection . prototype . _waitForConnect = async function _waitForConnect ( noTimeout ) {
826
827
if ( ( this . readyState === STATES . connecting || this . readyState === STATES . disconnected ) && this . _shouldBufferCommands ( ) ) {
827
828
const bufferTimeoutMS = this . _getBufferTimeoutMS ( ) ;
828
829
let timeout = null ;
829
830
let timedOut = false ;
830
831
// The element that this function pushes onto `_queue`, stored to make it easy to remove later
831
832
const queueElement = { } ;
832
- await Promise . race ( [
833
- new Promise ( resolve => {
834
- queueElement . fn = resolve ;
835
- this . _queue . push ( queueElement ) ;
836
- } ) ,
837
- new Promise ( resolve => {
838
- timeout = setTimeout (
839
- ( ) => {
840
- timedOut = true ;
841
- resolve ( ) ;
842
- } ,
843
- bufferTimeoutMS
844
- ) ;
845
- } )
846
- ] ) ;
833
+
834
+ // Mongoose executes all elements in `_queue` when initial connection succeeds in `onOpen()`.
835
+ const waitForConnectPromise = new Promise ( resolve => {
836
+ queueElement . fn = resolve ;
837
+ this . _queue . push ( queueElement ) ;
838
+ } ) ;
839
+
840
+ if ( noTimeout ) {
841
+ await waitForConnectPromise ;
842
+ } else {
843
+ await Promise . race ( [
844
+ waitForConnectPromise ,
845
+ new Promise ( resolve => {
846
+ timeout = setTimeout (
847
+ ( ) => {
848
+ timedOut = true ;
849
+ resolve ( ) ;
850
+ } ,
851
+ bufferTimeoutMS
852
+ ) ;
853
+ } )
854
+ ] ) ;
855
+ }
847
856
848
857
if ( timedOut ) {
849
858
const index = this . _queue . indexOf ( queueElement ) ;
Original file line number Diff line number Diff line change @@ -1112,7 +1112,7 @@ Model.init = function init() {
1112
1112
) ;
1113
1113
if ( autoCreate == null ) {
1114
1114
// `autoCreate` may later be set when the connection is opened, so wait for connect before checking
1115
- await conn . _waitForConnect ( ) ;
1115
+ await conn . _waitForConnect ( true ) ;
1116
1116
autoCreate = utils . getOption (
1117
1117
'autoCreate' ,
1118
1118
this . schema . options ,
You can’t perform that action at this time.
0 commit comments