我正在尝试连接到 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"
},