1

我正在尝试连接到 MongoDB Atlas 集群,但我的 react 应用程序出现问题。上await client.connect(),我明白了TypeError: Cannot read property 'replace' of undefined

我已经验证连接字符串可以通过 MongoDB Compass 工作。

我的 mongo.ts 文件

import { MongoClient } from 'mongodb';

const username = encodeURIComponent(process.env.REACT_APP_MONGO_READ_USERID as string);
const userpass = encodeURIComponent(process.env.REACT_APP_MONGO_READ_USERPASS as string);
const uri = `mongodb+srv://${username}:${userpass}@cluster0.xup6s.mongodb.net/database?w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

export const getItemsfromMongo = async <T>(collection: string): Promise<T[]> => {
    try {

        console.log(client);
        try {
            await client.connect(); // Fails here
            console.log(client);
        } catch (error) {
            console.error('Failed to connect to MongoDB server');
            throw error;
        }

        const mongoCollection = client.db("database").collection<T>(collection);
        const cursor = mongoCollection.find()
        const items = await cursor.toArray();

        console.log(items);

        await client.close();

        return items;
    } catch (err) {
        console.error(err);
        return [];
    }
}

package.json 依赖项

  "dependencies": {
    "@material-ui/core": "^4.10.1",
    "@material-ui/icons": "^4.9.1",
    "@types/mongodb": "^3.5.26",
    "bootstrap": "^4.5.0",
    "firebase": "^7.19.0",
    "mongodb": "^3.6.0",
    "mongodb-client-encryption": "^1.1.0",
    "node-sass": "^4.14.1",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "3.4.3",
    "realm": "^10.0.0-beta.6",
    "require_optional": "^1.0.1",
    "typescript": "^4.0.2"
  },
4

1 回答 1

1

我今天在做大致相同的事情时遇到了同样的错误。在进行了一些挖掘之后,我发现当您尝试使用前端应用程序执行后端功能时往往会发生此错误,在这种情况下,该功能似乎是 NodeJS 驱动程序。因此,我假设您在前端应用程序的某处调用导出的函数。由于各种原因,这是有问题的,但除了最佳实践之外,这永远不会奏效。我的建议是使用 REST API、GraphQL 或 MongoDB Stitch Browser SDK。我用了梯子,它对我很有用。

于 2021-04-06T06:27:39.207 回答