Skip to content

Instantly share code, notes, and snippets.

@midnightcodr
Created December 9, 2018 03:42
Show Gist options
  • Save midnightcodr/857e9c755505f3b951fe2d95439e87e0 to your computer and use it in GitHub Desktop.
Save midnightcodr/857e9c755505f3b951fe2d95439e87e0 to your computer and use it in GitHub Desktop.
test-mongo-db-cluster
start_cluster
docker exec -it rc1 mongo
# then run the following in container rc1's mongo shell
rs.initiate(config = { _id: 'test-set', members: [{ _id: 0, host: 'rc1:27017' }, { _id: 1, host: 'rc2:27017' }, { _id: 2, host: 'rc3:27017' }] })
# while in there, populate some test data
use test
db.list.insertOne({ somekey: 'some value' })
db.list.insertOne({ title: 'cool' })
# finally quit
quit()
# once back to the docker host shell
docker stop rc1 rc2 rc3
# now the whole script 
test-cluster
config = {
_id: 'test-set',
members: [
{ _id: 0, host: 'rc1:27017' },
{ _id: 1, host: 'rc2:27017' },
{ _id: 2, host: 'rc3:27017' }
]
}
start_cluster() {
for i in 1 2 3; do docker run --rm -p 3000$i:27017 --name rc$i --net mongo-cluster -v ~/docker-storage/rc$i:/data/db -d mongo mongod --replSet test-set; done
}
runnode() {
[ $# -lt 1 ] && echo "Usage: $FUNCNAME script" && return
scriptname=$1
shift
others=$*
docker run -it --rm --name my-node-script -v "$PWD":/usr/src/app -w /usr/src/app $others node:8 node $scriptname
}
test-cluster() {
start_cluster
until curl -s http://127.0.0.1:30003/ > /dev/null; do
sleep 1
done
echo "mongo replSet memebers are up"
echo "now wait for primary"
until docker exec -it rc3 mongo --eval "rs.status()" | grep -q PRIMARY; do
sleep 1;
done
# sleep extra time to make sure the replicaSet is ready for use
sleep 2
echo "primary is elected"
cd ~/projects/test-mongodb
runnode tt.js "--net=mongo-cluster"
}
const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://rc1:27017,rc2:27017,rc3:27017/test?replicaSet=test-set'
const db = 'test'
const main = async () => {
console.log('start')
const client = await MongoClient.connect(url, { useNewUrlParser: true })
const col = client.db(db).collection('list')
const res = await col.find({}, { limit: 5 }).toArray()
console.log(res)
await client.close()
console.log('end')
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment