jeudi 5 septembre 2019

Transaction numbers are only allowed on storage engines that support document-level locking - MongodbMemoryServer/Mochai/Chai/Supertest

I use Mocha / Chai / Supertest and Mongodb-Memory-Server to test my app. But's I received error: Transaction numbers are only allowed on storage engines that support document-level locking

In real database and test by postman, it's working well.

My code:

In database.js

const mongoose = require('mongoose')
const { MongoMemoryReplSet } = require('mongodb-memory-server')

mongoose.set('useFindAndModify', false);
const connect = async () => {
    try {
        let url = process.env.MONGO_URL

        let options = {
            //Something
        }
        if (process.env.NODE_ENV === 'test') {
            const replSet = new MongoMemoryReplSet();
            await replSet.waitUntilRunning();
            const uri = await replSet.getUri();

            await mongoose.connect(uri, options)

            //log connected
        } else {
            await mongoose.connect(url, options)
            //log connected
        }
    } catch (error) {
        //error
    }
}

I have two model: Company and User. I made a function to add a member to company with used transaction. My code

const addMember = async (req, res, next) => {
    const { companyId } = req.params
    const { userId } = req.body

    const session = await mongoose.startSession()
    try {
        await session.withTransaction(async () => {
            const [company, user] = await Promise.all([
                Company.findOneAndUpdate(
                    //Something
                ).session(session),

                User.findByIdAndUpdate(
                    //Something
                ).session(session)
            ])

            //Something if... else

            return res.json({
                message: `Add member successfully!`,
            })
        })
    } catch (error) {
        //error
    }
}

Here's router:

router.post('/:companyId/add-member',
    authentication.required,
    company.addMember
)

Test file:

const expect = require('chai').expect
const request = require('supertest')
const app = require('../app')

describe('POST /company/:companyId/add-member', () => {
    it('OK, add member', done => {
        request(app).post(`/company/${companyIdEdited}/add-member`)
        .set({ "x-access-token": signedUserTokenKey })
        .send({userId: memberId})
        .then(res => {
            console.log(res.body)
            expect(res.statusCode).to.equals(200)
            done()
        })
        .catch((error) => done(error))
    })
})

And i received error: Transaction numbers are only allowed on storage engines that support document-level locking'

How can I fix this?

Aucun commentaire:

Enregistrer un commentaire