Node.js连接MongoDB报错:ReferenceError: Client is not defined求助
Hey there! That error usually pops up when you're referencing a Client variable that hasn't been properly imported or named correctly. Let's walk through the fixes step by step:
1. Double-check your MongoDB import
First, make sure you've installed the official MongoDB driver:
npm install mongodb
Then, ensure you're importing the correct named export from the package. The driver exports MongoClient (not just Client), so you need to destructure it properly:
- For CommonJS (using
require, most Node.js projects):const { MongoClient } = require('mongodb'); - For ES Modules (using
import, if your project usestype: moduleinpackage.json):import { MongoClient } from 'mongodb';
2. Fix your connection call
The error mentions MongoClient.connect in the stack trace, but it’s likely you accidentally used Client.connect somewhere in your code. Here’s what a working connection snippet looks like:
const { MongoClient } = require('mongodb'); const dbURI = 'mongodb://localhost:27017/your-database-name'; // Replace with your actual URI // Callback-style connection MongoClient.connect(dbURI, (err, client) => { if (err) { console.error('Failed to connect:', err); return; } console.log('Successfully connected to MongoDB!'); // Do your database operations here client.close(); // Don't forget to close the connection when done });
3. Bonus: Use async/await (modern approach)
If you’re using Node.js 14+, async/await makes the code cleaner and easier to debug:
const { MongoClient } = require('mongodb'); const dbURI = 'mongodb://localhost:27017/your-database-name'; async function connectToMongo() { let client; try { client = await MongoClient.connect(dbURI); console.log('Connected to MongoDB successfully!'); // Perform database actions here } catch (err) { console.error('Connection error:', err); } finally { if (client) { await client.close(); console.log('Connection closed.'); } } } connectToMongo();
Key Takeaway
The root issue is that you’re using an undefined Client variable instead of the correctly imported MongoClient. Double-check your import statement and every place you call the connection method—replacing Client with MongoClient should resolve the error.
内容的提问来源于stack exchange,提问作者Leon Bogod

