MongoDB Replica Set for Local Debugging with Prisma

오픈소스·2023년 4월 10일
0

MongoDB with Prisma

목록 보기
3/4
post-thumbnail
Invalid `this.prisma.user.create()` invocation in
/Users/youngkiu/src/nestjs-kakaologin/src/user/user.service.ts:20:29

  17 
  18 async create(data: Prisma.UserCreateInput): Promise<User> {
  19   // https://www.prisma.io/docs/getting-started/setup-prisma/start-from-scratch/mongodb/querying-the-database-typescript-mongodb#write-data-into-the-database20   return this.prisma.user.create(
Prisma needs to perform transactions, which requires your MongoDB server to be run as a replica set. https://pris.ly/d/mongodb-replica-set

위와 같은 에러로 MongoDB에 insert가 되지 않았습니다.
(https://www.prisma.io/docs/concepts/database-connectors/mongodb#replica-set-configuration)

  • docker-compose.yml
...
  mongo:
    container_name: local-mongo
    image: mongo:5.0.15
    restart: always
    ports:
      - ${MONGO_PORT}:27017
    environment:
      - MONGO_INITDB_ROOT_USERNAME=${MONGO_USER}
      - MONGO_INITDB_ROOT_PASSWORD=${MONGO_PW}
      - MONGO_INITDB_DATABASE=${MONGO_DB}
    volumes:
      - ./mongodb:/data/db
      - ./:/opt/keyfile/
    command: "--bind_ip_all --keyFile /opt/keyfile/keyfile --replSet rs0"
$ docker-compose up mongo
$ docker exec -it local-mongo bash
root@f9b5d1203ce4:/# mongosh -u <MONGO_INITDB_ROOT_USERNAME> -p <MONGO_INITDB_ROOT_PASSWORD> 
Current Mongosh Log ID: 64338c90c75cf191f8a3d93d
Connecting to:          mongodb://<credentials>@127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.8.0
Using MongoDB:          5.0.15
Using Mongosh:          1.8.0

For mongosh info see: https://docs.mongodb.com/mongodb-shell/


To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.

------
   Enable MongoDB's free cloud-based monitoring service, which will then receive and display
   metrics about your deployment (disk utilization, CPU, operation statistics, etc).
   
   The monitoring data will be available on a MongoDB website with a unique URL accessible to you
   and anyone you share the URL with. MongoDB may use this information to make product
   improvements and to suggest MongoDB products and deployment options to you.
   
   To enable free monitoring, run the following command: db.enableFreeMonitoring()
   To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
------

test> config = {
        "_id" : "rs0", // docker-compose에 있는 replSet과 동일하게
        "members" : [
                {
                        "_id" : 0,
                        "host" : "localhost:27017"
                }
        ]
    }
{ _id: 'rs0', members: [ { _id: 0, host: 'localhost:27017' } ] }
test> rs.initiate(config)
{ ok: 1 }
rs0 [direct: other] test> 

prisma/schema.prisma 화일은 미리 준비되어 있습니다.

$ npx prisma db push              
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": MongoDB database "chat" at "localhost:27017"
Applying the following changes:

[+] Collection `User`
[+] Collection `Chat`
[+] Unique index `User_provider_providerId_key` on ({"provider":1,"providerId":1})


🚀  Your database indexes are now in sync with your Prisma schema. Done in 78ms

✔ Generated Prisma Client (4.12.0 | library) to ./node_modules/@prisma/client in 45ms

Troubleshooting

  • rs.initiate() 없이 npx prisma db push 실행하면 다음과 같은 에러가 발생합니다.

    $ npx prisma db push                
    Environment variables loaded from .env
    Prisma schema loaded from prisma/schema.prisma
    Datasource "db": MongoDB database "chat" at "localhost:27017"
    Error: MongoDB error
    Server selection timeout: None of the available servers suitable for criteria Predicate. Topology: { Type: Unknown, Servers: [ { Address: localhost:27017, Type: RsGhost, Average RTT: 4.023226ms, Last Update Time: DateTime(OffsetDateTime { local_datetime: PrimitiveDateTime { date: Date { year: 2023, ordinal: 100 }, time: Time { hour: 5, minute: 4, second: 37, nanosecond: 35000000 } }, offset: UtcOffset { hours: 0, minutes: 0, seconds: 0 } }), Max Wire Version: 13, Min Wire Version: 0 }, ] }
     0: migration_core::commands::schema_push::Calculate `from`
               at migration-engine/core/src/commands/schema_push.rs:46
     1: migration_core::state::SchemaPush
               at migration-engine/core/src/state.rs:444
  • rs.initiate()를 한다고 하더라도, localhost에 대한 host를 가진 config 없이
    (https://www.mongodb.com/docs/manual/tutorial/convert-standalone-to-replica-set/)

    test> rs.initiate()
    {
    info2: 'no configuration specified. Using a default configuration for the set',
    me: '8d6d480cb324:27017',
    ok: 1
    }

    npx prisma db push 실행하면 다음과 같은 에러가 발생합니다.

    $ npx prisma db push
    Environment variables loaded from .env
    Prisma schema loaded from prisma/schema.prisma
    Datasource "db": MongoDB database "chat" at "localhost:27017"
    Error: MongoDB error
    Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: 8d6d480cb324:27017, Type: Unknown, Error: failed to lookup address information: nodename nor servname provided, or not known }, ] }
     0: migration_core::commands::schema_push::Calculate `from`
               at migration-engine/core/src/commands/schema_push.rs:46
     1: migration_core::state::SchemaPush
               at migration-engine/core/src/state.rs:444

참고)

2개의 댓글

comment-user-thumbnail
2023년 6월 9일

Hi bro,

I also have this issue. Could you share with me how to fix this problem?

Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: 8d6d480cb324:27017, Type: Unknown, Error: failed to lookup address information: nodename nor servname provided, or not known }, ] }

Thanks a lot!

1개의 답글