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

withSession #14339

Merged
merged 7 commits into from Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 22 additions & 0 deletions lib/connection.js
Expand Up @@ -443,6 +443,28 @@ Connection.prototype.createCollections = async function createCollections(option
return result;
};

/**
* A convenience wrapper for `connection.client.withSession()`.
*
* #### Example:
*
* await conn.withSession(async session => {
* const doc = await TestModel.findOne().session(session);
* });
*
* @method withSession
* @param {Function} executor called with 1 argument: a `ClientSession` instance
* @return {Promise} resolves to the return value of the executor function
* @api public
*/

Connection.prototype.withSession = async function withSession(executor) {
if (arguments.length === 0) {
throw new Error('Please provide an executor function');
}
return await this.client.withSession(executor);
};

/**
* _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://www.mongodb.com/docs/manual/release-notes/3.6/#client-sessions)
* for benefits like causal consistency, [retryable writes](https://www.mongodb.com/docs/manual/core/retryable-writes/),
Expand Down
12 changes: 12 additions & 0 deletions test/connection.test.js
Expand Up @@ -1553,6 +1553,18 @@ describe('connections:', function() {
});
assert.deepEqual(m.connections.length, 0);
});
it('should demonstrate the withSession() function (gh-14330)', async function() {
if (!process.env.REPLICA_SET && !process.env.START_REPLICA_SET) {
this.skip();
}
const m = new mongoose.Mongoose();
m.connect(start.uri);
let session = null;
await m.connection.withSession(s => {
session = s;
});
assert.ok(session);
});
describe('createCollections()', function() {
it('should create collections for all models on the connection with the createCollections() function (gh-13300)', async function() {
const m = new mongoose.Mongoose();
Expand Down
2 changes: 2 additions & 0 deletions types/connection.d.ts
Expand Up @@ -240,6 +240,8 @@ declare module 'mongoose' {

/** Watches the entire underlying database for changes. Similar to [`Model.watch()`](/docs/api/model.html#model_Model-watch). */
watch<ResultType extends mongodb.Document = any>(pipeline?: Array<any>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;

withSession<T = any>(executor: (session: ClientSession) => Promise<T>): T;
}

}