|
18 | 18 | } |
19 | 19 |
|
20 | 20 | wait_for_mongodb() { |
21 | | - local max_tries=30 |
| 21 | + local max_tries=60 |
22 | 22 | local try=1 |
23 | 23 |
|
24 | | - until node --input-type=module -e "import { MongoClient } from 'mongodb'; const c = new MongoClient(process.env.ATLAS_URI); await c.connect(); await c.db('admin').command({ ping: 1 }); await c.close();" >/dev/null 2>&1; do |
| 24 | + # Atlas Local uses a replica set — wait until a writable primary is elected, |
| 25 | + # not just until mongod responds to ping (which happens before primary election). |
| 26 | + until node --input-type=module -e " |
| 27 | + import { MongoClient } from 'mongodb'; |
| 28 | + const c = new MongoClient(process.env.ATLAS_URI); |
| 29 | + await c.connect(); |
| 30 | + const h = await c.db('admin').command({ hello: 1 }); |
| 31 | + await c.close(); |
| 32 | + if (!h.isWritablePrimary) throw new Error('no primary yet'); |
| 33 | + " >/dev/null 2>&1; do |
25 | 34 | if (( try >= max_tries )); then |
26 | | - echo "MongoDB did not become ready in time." |
| 35 | + echo "MongoDB primary did not become ready in time." |
27 | 36 | return 1 |
28 | 37 | fi |
29 | | - echo "Waiting for MongoDB... ($try/$max_tries)" |
| 38 | + echo "Waiting for MongoDB primary... ($try/$max_tries)" |
30 | 39 | try=$((try + 1)) |
31 | 40 | sleep 2 |
32 | 41 | done |
33 | | -} |
34 | | - |
35 | | -seed_database() { |
36 | | - ( |
37 | | - cd "$SERVER_DIR" |
38 | | - node --env-file=config.env seed.js > /tmp/mern-seed.log 2>&1 |
39 | | - ) |
40 | | - |
41 | | - echo "Seed completed (log: /tmp/mern-seed.log)." |
42 | | -} |
43 | | - |
44 | | -verify_seed_data() { |
45 | | - local count |
46 | | - |
47 | | - count=$( |
48 | | - cd "$SERVER_DIR" && |
49 | | - node --env-file=config.env --input-type=module -e "import { MongoClient } from 'mongodb'; const c = new MongoClient(process.env.ATLAS_URI); await c.connect(); const n = await c.db('employees').collection('records').countDocuments(); console.log(n); await c.close();" |
50 | | - ) |
51 | | - |
52 | | - echo "Seed verification: employees.records has $count documents." |
53 | | - |
54 | | - if [[ "$count" -le 0 ]]; then |
55 | | - echo "Seed verification failed: no documents found in employees.records." |
56 | | - echo "Seed log tail:" |
57 | | - tail -n 50 /tmp/mern-seed.log || true |
58 | | - return 1 |
59 | | - fi |
| 42 | + echo "MongoDB primary is ready." |
60 | 43 | } |
61 | 44 |
|
62 | 45 | start_server_if_needed() { |
@@ -87,9 +70,5 @@ start_client_if_needed() { |
87 | 70 |
|
88 | 71 | ensure_config |
89 | 72 | wait_for_mongodb |
90 | | -seed_database |
91 | | -verify_seed_data |
92 | | -start_server_if_needed |
93 | | -start_client_if_needed |
94 | 73 |
|
95 | 74 | echo "Codespaces startup complete." |
0 commit comments