跳到主要內容

使用 TypeScript 和 MongoDB 連線資料庫

要連線你的資料庫,你需要將 Prisma schema 中 datasource 塊的 url 欄位設定為你的資料庫連線 URL

prisma/schema.prisma
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}

在這種情況下,url 透過環境變數設定,該變數在 .env 中定義(示例使用 MongoDB Atlas URL)

.env
DATABASE_URL="mongodb+srv://test:test@cluster0.ns1yp.mongodb.net/myFirstDatabase"

現在你需要調整連線 URL,使其指向你自己的資料庫。

你的資料庫的連線 URL 格式取決於你使用的資料庫。對於 MongoDB,它看起來如下(所有大寫的部分是你的特定連線詳細資訊的佔位符

mongodb://USERNAME:PASSWORD@HOST:PORT/DATABASE

以下是每個元件的簡要說明

  • USERNAME: 你的資料庫使用者名稱
  • PASSWORD: 你的資料庫使用者密碼
  • HOST: mongod(或 mongos)例項執行的主機
  • PORT: 你的資料庫伺服器執行的埠(MongoDB 通常為 27017
  • DATABASE: 資料庫的名稱。請注意,如果你使用的是 MongoDB Atlas,你需要手動將資料庫名稱附加到連線 URL 的末尾,因為 MongoDB Atlas 的環境連結不包含它。

故障排除

Error in connector: SCRAM failure: Authentication failed.

如果你看到 Error in connector: SCRAM failure: Authentication failed. 錯誤訊息,你可以透過在連線字串末尾新增 ?authSource=admin 來指定用於身份驗證的源資料庫。

Raw query failed. Error code 8000 (AtlasError): empty database name not allowed.

如果你看到 Raw query failed. Code: unknown. Message: Kind: Command failed: Error code 8000 (AtlasError): empty database name not allowed. 錯誤訊息,請務必將資料庫名稱附加到資料庫 URL。你可以在此 GitHub issue 中找到更多資訊。

© . This site is unofficial and not affiliated with Prisma Data, Inc.