MongoClient instance has a built-in connection pool. Reuse the same instance throughout your application to avoid creating a new connection for each request. For web frameworks such as Express or Koa, we recommend establishing the connection at application startup and sharing it through middleware or dependency injection.MongoNetworkError) and operation errors (MongoServerError), and handle each accordingly.npm install mongodb
Operating System: Ubuntu 24.04.3 LTS / x86_64
Runtime Version: GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)
const { MongoClient } = require("mongodb");// Connection URI (Replace with your actual connection information)const uri = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin";// Replica set connection string (Recommended):// const uri = "mongodb://mongouser:thepasswordA1@IP1:27017,IP2:27017,IP3:27017/admin?replicaSet=cmgo-xxxxxxxx_0";// Create a client (Configure connection pool parameters)const client = new MongoClient(uri, {maxPoolSize: 50, // Maximum size of the connection poolminPoolSize: 5, // Minimum size of the connection poolconnectTimeoutMS: 10000, // Connection timeout of 10 secondssocketTimeoutMS: 30000, // Socket timeout of 30 secondsretryWrites: true, // Enable retryable writesretryReads: true, // Enable retryable readsw: "majority", // Write concern level});async function main() {try {// Establish a connection.await client.connect();console.log("Connection successful");// Select a database and a collection.const db = client.db("mydb");const collection = db.collection("users");// ========== Insert a Document ==========const insertResult = await collection.insertOne({username: "jack",age: 31,email: "jack@example.com",createdAt: new Date(),});console.log(`Inserted document ID: ${insertResult.insertedId}`);// Batch Insertconst insertManyResult = await collection.insertMany([{ username: "alice", age: 28, email: "alice@example.com" },{ username: "bob", age: 35, email: "bob@example.com" },]);console.log(`Batch inserted ${insertManyResult.insertedCount} documents`);// ========== Query Documents ==========const user = await collection.findOne({ username: "jack" });console.log("Query a single document:", user);// Conditional Query (Age greater than 30)const cursor = collection.find({ age: { $gt: 30 } });console.log("Users with age greater than 30:");for await (const doc of cursor) {console.log(` - ${doc.username}, Age: ${doc.age}`);}// ========== Update Documents ==========const updateResult = await collection.updateOne({ username: "jack" },{ $set: { age: 32, updatedAt: new Date() } });console.log(`Updated ${updateResult.modifiedCount} documents`);// ========== Delete Documents ==========const deleteResult = await collection.deleteMany({username: { $in: ["jack", "alice", "bob"] },});console.log(`Deleted ${deleteResult.deletedCount} documents`);} catch (error) {console.error("Operation failed:", error.message);} finally {await client.close();console.log("Connection closed");}}main();
Connection successfulInserted document ID: 6789abcdef1234567890abcdBatch Insert 2 DocumentsQuery a single document: { _id: ObjectId('6789abcdef1234567890abcd'), username: 'jack', age: 31, email: 'jack@example.com', createdAt: 2026-04-17T07:00:00.000Z }Users with age greater than 30:- jack, age: 31- bob, age: 35Update 1 DocumentDelete 3 DocumentsThe connection has been closed.
npm install mongoose
Operating System: Ubuntu 24.04.3 LTS / x86_64
Runtime Version: GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)
/mydb) in the URI, and specify the authentication database as admin via ?authSource=admin.const mongoose = require("mongoose");// Connection URI (Replace with your actual connection information)const uri = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb?authSource=admin";async function main() {try {// Establish a connection.await mongoose.connect(uri, {maxPoolSize: 50,minPoolSize: 5,connectTimeoutMS: 10000,socketTimeoutMS: 30000,});console.log("Mongoose connection successful");// Define the Schemaconst userSchema = new mongoose.Schema({username: { type: String, required: true, unique: true },age: { type: Number, min: 0 },email: { type: String },createdAt: { type: Date, default: Date.now },});// Create the Modelconst User = mongoose.model("User", userSchema);// Insert a documentconst user = await User.create({username: "jack",age: 31,email: "jack@example.com",});console.log("Inserted document:", user);// Query the documentconst found = await User.findOne({ username: "jack" });console.log("Query result:", found);// Update the documentawait User.updateOne({ username: "jack" }, { $set: { age: 32 } });console.log("Update completed.");// Delete the documentawait User.deleteOne({ username: "jack" });console.log("Deletion completed.");} catch (error) {console.error("Operation failed:", error.message);} finally {await mongoose.disconnect();console.log("Connection closed");}}main();
MongoServerError: Authentication failed.
admin in the URI.// Correct: The URI path is /admin.const uri1 = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin";// Correct: Specify the authentication database via the authSource parameter when connecting to the business database.const uri2 = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb?authSource=admin";// Error: When connecting to the business database without specifying authSource, the driver defaults to authenticating with the mydb database, causing authentication to fail.const uri3 = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb";
Operating System: Ubuntu 24.04.3 LTS / x86_64
Runtime Version: Node.js v22.13.1
encodeURIComponent() to encode the password.const password = encodeURIComponent("pass@123"); // Output: pass%40123const uri = `mongodb://mongouser:${password}@10.66.187.127:27017/admin`;
Operating System: Ubuntu 24.04.3 LTS / x86_64
Runtime Version: Node.js v22.13.1
MongoNetworkTimeoutError: connection timed out
MongoNetworkError: connect ECONNREFUSED 10.66.187.127:27017
telnet <MongoDB-instance-IP> 27017
Connected indicates that the network is reachable. Check the authentication configuration.Connection timed out or Connection refused, it indicates a network connectivity issue. Confirm that the CVM and the MongoDB instance are in the same VPC and check the security group rules.connectTimeoutMS configuration value is reasonable.const client = new MongoClient(uri, {connectTimeoutMS: 10000, // Connection timeout of 10 secondssocketTimeoutMS: 30000, // Socket timeout of 30 seconds});
replicaSet parameter matches the replica set name on the instance details page in the console.MongooseServerSelectionError: connect ECONNREFUSED 10.66.187.127:27017
// Correct: Specify the business database /mydb and the authentication database via the authSource parameter.await mongoose.connect("mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb?authSource=admin");// Error: The authSource parameter is missing.await mongoose.connect("mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb");
useNewUrlParser and useUnifiedTopology). If you are using a newer version of Mongoose, do not pass these deprecated parameters:// Mongoose 6.x and above (Correct, no additional parameters required)await mongoose.connect(uri, {maxPoolSize: 50,connectTimeoutMS: 10000,});// Mongoose 5.x (requires the following parameters)await mongoose.connect(uri, {useNewUrlParser: true,useUnifiedTopology: true,});
フィードバック