我正在尝试连接到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"
},
答案 0 :(得分:1)
我今天在做大致相同的事情时遇到了同样的错误。在进行了一些挖掘之后,我发现当您尝试使用前端应用程序执行后端功能时,往往会发生此错误,在这种情况下,后端功能似乎是一个 NodeJS 驱动程序。因此,我假设您正在前端应用程序中的某处调用导出的函数。出于多种原因,这存在问题,但除了最佳实践之外,这永远不会奏效。我的建议是使用 REST API、GraphQL 或 MongoDB Stitch Browser SDK。我使用了梯子,它对我很有用。