[BUG.v5.2.1] ClientSession cannot be serialized to BSON - Sessions

See original GitHub issue

Hello; trying to use simple transaction case as described in the documentation; I’m getting an error

ClientSession cannot be serialized to BSON.
    at ClientSession.toBSON (/eliot-local-git/node_modules/mongoose/node_modules/mongodb-core/lib/sessions.js:225:11)
    at serializeInto (/eliot-local-git/node_modules/bson/lib/bson/parser/serializer.js:895:23)
    at serializeObject (/eliot-local-git/node_modules/bson/lib/bson/parser/serializer.js:347:18)
    at serializeInto (/eliot-local-git/node_modules/bson/lib/bson/parser/serializer.js:937:17)
    at BSON.serialize (/eliot-local-git/node_modules/bson/lib/bson/bson.js:63:28)
    at Query.toBin (/eliot-local-git/node_modules/mongoose/node_modules/mongodb-core/lib/connection/commands.js:144:25)
    at serializeCommands (/eliot-local-git/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:1044:43)
    at Pool.write (/eliot-local-git/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:1260:3)
    at Cursor._find (/eliot-local-git/node_modules/mongoose/node_modules/mongodb-core/lib/cursor.js:326:22)
    at nextFunction (/eliot-local-git/node_modules/mongoose/node_modules/mongodb-core/lib/cursor.js:673:10)
    at Cursor.next (/eliot-local-git/node_modules/mongoose/node_modules/mongodb-core/lib/cursor.js:824:3)
    at Cursor._next (/eliot-local-git/node_modules/mongoose/node_modules/mongodb/lib/cursor.js:211:36)
    at nextObject (/eliot-local-git/node_modules/mongoose/node_modules/mongodb/lib/operations/cursor_ops.js:186:10)
    at next (/eliot-local-git/node_modules/mongoose/node_modules/mongodb/lib/operations/cursor_ops.js:165:3)
    at executeOperation (/eliot-local-git/node_modules/mongoose/node_modules/mongodb/lib/utils.js:420:24)
    at Cursor.next (/eliot-local-git/node_modules/mongoose/node_modules/mongodb/lib/cursor.js:253:10)

My code look like :

        const session = await model.startSession();

        const oneCompany = await model.findOne({}, {
          projection: '_id',
          session,
        });

        const oneLanguage = await classes.Language.schema.getModel().findOneAndUpdate({
          _id: 'aaaaa0000000000000000000',
        }, {
          'name.description': 'lelz',
        }, {
          new: true,
          projection: '_id',
          session,
        });

        await session.commitTransaction();

        session.endSession();

Versions I use :

node.js v9.11.1 mongoose@5.2.1 mongodb@3.1.0 (mongo native node driver) mongodb-core@3.1.0 (mongo native node driver) mongodb v4.0.0 (database)

Thanks

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:6

github_iconTop GitHub Comments

12reactions
vkarpov15commented, Jul 4, 2018

This is a common gotcha that we should add docs for, but your issue is that the 2nd arg to Model.findOne() is always a projection. You need to do await A.findOne({}, null, { session });

0reactions
zinzindaycommented, Jul 13, 2018

const {MongoClient} = require('mongodb');
const uri = 'mongodb://localhost:27017,localhost:27018,localhost:27019/test-mongodb';
MongoClient.connect(uri, {useNewUrlParser: true, replicaSet: 'rs'}).then(async (client) => {
    // console.log(client);
    const db = client.db();
    await db.dropDatabase();

    await db.collection('Account').insertMany([
        {name: 'A', balance: 5},
        {name: 'B', balance: 10}
    ]);

    await transfer('A', 'B', 4); // Success
    try {
        await transfer('A', 'B', 6);
    } catch (error) {
        console.log(error);
    }
    // The actual transfer logic
    async function transfer(from, to, amount) {
        const session = client.startSession();
        session.startTransaction();
        try {
            const opts = {session, returnOriginal: false};
            const B = await db.collection('Account').findOneAndUpdate({name: to}, {$inc: {balance: amount}}, opts).then(res => res.value);
            const A = await db.collection('Account').findOneAndUpdate({name: from}, {$inc: {balance: -amount}}, opts).then(res => res.value);
            if (A.balance < 0) {
                // If A would have negative balance, fail and abort the transaction
                // `session.abortTransaction()` will undo the above `findOneAndUpdate()`
                throw new Error('Insufficient funds: ' + (A.balance + amount));
            }
            await session.commitTransaction();
            session.endSession();
            return {from: A, to: B};
        } catch (error) {
            // If an error occurred, abort the whole transaction and
            // undo any changes that might have happened
            await session.abortTransaction();
            session.endSession();
            throw error; // Rethrow so calling function sees error
        }
    }
}).catch(console.log);


@vkarpov15 your example worked

Read more comments on GitHub >

github_iconTop Results From Across the Web

ClientSession cannot be serialized to BSON - Mongodb ...
turns out I have to pass session on the 3rd parameter on find method and wrap payload as an array on create method...
Read more >
mongodb - UNPKG
180, export declare interface AbstractCursorOptions extends BSONSerializeOptions {. 181, session?: ClientSession;. 182, readPreference?: ReadPreferenceLike;.
Read more >
mongoose | Yarn - Package Manager
Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports Node.js and Deno (alpha). Build Status NPM...
Read more >
Spring Data MongoDB - Reference Documentation
Improved support for <mongo:mongo-client credentials="…​" /> . Improved index creation failure error message. 6.11. What's New in Spring Data ...
Read more >
A MongoDB Collection - metacpan.org
Cannot be specified together with resumeAfter . Plain values will be coerced to BSON::Timestamp objects. session - the session to use for these...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found