I'm trying to use the replicaset feature from mongodb-memory-server.
With this snippet:
const test = require('ava');
const { MongoMemoryReplSet } = require('mongodb-memory-server');
const { MongoClient } = require('mongodb');
const mongoReplSet = new MongoMemoryReplSet({
debug: true,
replSet: {
count: 3,
configSettings: { electionTimeoutMillis: 500 }
}
});
test.before('Init', async () => {
await mongoReplSet.waitUntilRunning();
process.env.MONGODB_URI = `${await mongoReplSet.getConnectionString()}?replicaSet=testset`;
console.log('process.env.MONGODB_URI:', process.env.MONGODB_URI);
process.env.MONGODB_DBNAME = await mongoReplSet.getDbName();
console.log('process.env.MONGODB_DBNAME:', process.env.MONGODB_DBNAME);
const mongoClient = await MongoClient.connect(process.env.MONGODB_URI, { useNewUrlParser: true });
const dbConn = mongoClient.db(process.env.MONGODB_DBNAME);
dbConn.on('close', () => logger.warn('MongoDB event `close`'));
dbConn.on('error', (err) => logger.warn('MongoDB event `error`:', err)); // eslint-disable-line promise/prefer-await-to-callbacks
dbConn.on('fullsetup', () => logger.info('MongoDB event `fullsetup`'));
dbConn.on('reconnect', () => logger.info('MongoDB event `reconnect`'));
dbConn.on('timeout', () => logger.warn('MongoDB event `timeout`'));
});
test('Success!', (t) => {
t.truthy(true);
});
I get:
MongoError {
[Symbol(mongoErrorContextSymbol)]: {},
message: 'no primary found in replicaset or invalid replica set name',
}
@fracasula sounds related to your PR, any idea?
What if you use an electionTimeoutMillis: 10000 (10 seconds) which is the MongoDB default? Do you still get the error?
Still MongoError: no primary found in replicaset or invalid replica set name

And something the three nodes' state is SECONDARY
I had (actually still have) issues with the waitUntilRunning function which seems to be returning before the cluster is ready.
In my code I had to do the following:
export const wait = (t: number) => new Promise(res => setTimeout(res, t))
// init your replica set here
// ...
await replicaSet.waitUntilRunning()
await wait(2000) // sleep a bit before connecting to the servers
Might be worth trying to see if that's the case.
It works with await wait(2000)
Same behavior with mongodb-memory-server version 5.0.4
OK cool, guess you're having the same issue that I have. I didn't write that code and unfortunately I haven't had the time yet to look into it either.
:tada: This issue has been resolved in version 7.0.0-beta.1 :tada:
The release is available on:
Your semantic-release bot :package::rocket:
Marking Issue as stale, will be closed in 7 days if no more activity is seen
Closing Issue because it is marked as stale
:tada: This issue has been resolved in version 7.0.0 :tada:
The release is available on:
Your semantic-release bot :package::rocket:
Most helpful comment
:tada: This issue has been resolved in version 7.0.0-beta.1 :tada:
The release is available on:
Your semantic-release bot :package::rocket: