Skip to main content

将 MongoDB 数据库连接到现有的 TypeScript 项目

连接你的数据库

¥Connecting your database

要连接数据库,你需要将 Prisma 架构中 datasource 块的 url 字段设置为数据库 连接网址

¥To connect your database, you need to set the url field of the datasource block in your Prisma schema to your database connection URL:

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

在本例中,url.env 中定义的 通过环境变量设置

¥In this case, the url is set via an environment variable which is defined in .env:

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

你现在需要调整连接 URL 以指向你自己的数据库。

¥You now need to adjust the connection URL to point to your own database.

你的数据库的 连接 URL 的格式 取决于你使用的数据库。对于 MongoDB,它看起来如下(全大写的部分是特定连接详细信息的占位符):

¥The format of the connection URL for your database depends on the database you use. For MongoDB, it looks as follows (the parts spelled all-uppercased are placeholders for your specific connection details):

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

以下是每个组件的简短说明:

¥Here's a short explanation of each component:

  • USERNAME:你的数据库用户的名称

    ¥USERNAME: The name of your database user

  • PASSWORD:你的数据库用户的密码

    ¥PASSWORD: The password for your database user

  • HOST:运行 mongod(或 mongos)实例的主机

    ¥HOST: The host where a mongod (or mongos) instance is running

  • PORT:数据库服务器运行的端口(对于 MongoDB 通常为 27017

    ¥PORT: The port where your database server is running (typically 27017 for MongoDB)

  • DATABASE:数据库的名称。请注意,如果你使用的是 MongoDB Atlas,则需要手动将数据库名称附加到连接 URL,因为 MongoDB Atlas 的环境链接不包含它。

    ¥DATABASE: The name of the database. Note that if you're using MongoDB Atlas, you need to manually append the database name to the connection URL because the environment link from MongoDB Atlas doesn't contain it.

故障排除

¥Troubleshooting

Error in connector: SCRAM failure: Authentication failed.

如果你看到 Error in connector: SCRAM failure: Authentication failed. 错误消息,你可以通过 adding ?authSource=admin 在连接字符串末尾指定身份验证的源数据库。

¥If you see the Error in connector: SCRAM failure: Authentication failed. error message, you can specify the source database for the authentication by adding ?authSource=admin to the end of the connection string.

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 问题 中找到更多信息。

¥If you see the Raw query failed. Code: unknown. Message: Kind: Command failed: Error code 8000 (AtlasError): empty database name not allowed. error message, be sure to append the database name to the database URL. You can find more info in this GitHub issue.