tencent cloud

TencentDB for MongoDB

Node.js SDK

ダウンロード
フォーカスモード
フォントサイズ
最終更新日: 2026-06-11 11:36:11

Scenarios

Node.js is widely used in web backend services and serverless application development due to its event-driven and non-blocking I/O model. The official MongoDB Node.js Driver provides Promise-based asynchronous APIs that align naturally with Node.js's asynchronous programming model. This document walks you through a complete example of connecting to TencentDB for MongoDB using both the native driver and the Mongoose ODM library.

Prerequisites

You have created a TencentDB for MongoDB instance, and the instance status is Running.
You have prepared a CVM instance that resides in the same VPC as the MongoDB instance, and you have installed Node.js version 18 or later.

Must-Knows

Asynchronous Programming: MongoDB Node.js Driver 4.x and later fully adopts the Promise and async/await pattern. If your code still uses the callback style, we recommend migrating to async/await.
Connection Reuse: The 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.
Error Handling: In production environments, wrap database operations with proper exception handling. Distinguish between network errors (MongoNetworkError) and operation errors (MongoServerError), and handle each accordingly.

Method 1: Native MongoDB Driver

Installing a Driver

npm install mongodb

Running Environment

Operating System: Ubuntu 24.04.3 LTS / x86_64

Runtime Version: GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)

Connection and CRUD Operation Examples

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 pool
minPoolSize: 5, // Minimum size of the connection pool
connectTimeoutMS: 10000, // Connection timeout of 10 seconds
socketTimeoutMS: 30000, // Socket timeout of 30 seconds
retryWrites: true, // Enable retryable writes
retryReads: true, // Enable retryable reads
w: "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 Insert
const 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();
Sample Output:
Connection successful
Inserted document ID: 6789abcdef1234567890abcd
Batch Insert 2 Documents
Query 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: 35
Update 1 Document
Delete 3 Documents
The connection has been closed.

Method 2: Mongoose ORM

Mongoose is a mainstream MongoDB ORM framework for Node.js. It provides features such as Schema definition, data validation, and middleware, making it suitable for building structured applications.

Installing Mongoose

npm install mongoose

Running Environment

Operating System: Ubuntu 24.04.3 LTS / x86_64

Runtime Version: GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)

Connection and Operation Examples

When using Mongoose, directly specify the business database (such as /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 Schema
const 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 Model
const User = mongoose.model("User", userSchema);

// Insert a document
const user = await User.create({
username: "jack",
age: 31,
email: "jack@example.com",
});
console.log("Inserted document:", user);

// Query the document
const found = await User.findOne({ username: "jack" });
console.log("Query result:", found);

// Update the document
await User.updateOne({ username: "jack" }, { $set: { age: 32 } });
console.log("Update completed.");

// Delete the document
await 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();

FAQs

"MongoServerError: Authentication failed" During Connection

Error Message Example:
MongoServerError: Authentication failed.
Troubleshoot by following these steps:
1. Confirm that the authentication database is specified as 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";

Running Environment

Operating System: Ubuntu 24.04.3 LTS / x86_64

Runtime Version: Node.js v22.13.1

2. Confirm that special characters in the password are URL-encoded: Use encodeURIComponent() to encode the password.
const password = encodeURIComponent("pass@123"); // Output: pass%40123
const uri = `mongodb://mongouser:${password}@10.66.187.127:27017/admin`;

Running Environment

Operating System: Ubuntu 24.04.3 LTS / x86_64

Runtime Version: Node.js v22.13.1

3. Confirm that the username and password are correct: Log in to the MongoDB console and verify the user information on the instance management page. If you forget the password, you can reset it in the console.

"MongoNetworkTimeoutError" or "ECONNREFUSED" During Connection

Error Message Example:
MongoNetworkTimeoutError: connection timed out
Or:
MongoNetworkError: connect ECONNREFUSED 10.66.187.127:27017
Troubleshoot by following these steps:
1. Confirm network connectivity: Run the following command on the CVM to verify whether the network is reachable:
telnet <MongoDB-instance-IP> 27017
The output Connected indicates that the network is reachable. Check the authentication configuration.
If the output is 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.
2. Check the connection timeout configuration: Confirm that the connectTimeoutMS configuration value is reasonable.
const client = new MongoClient(uri, {
connectTimeoutMS: 10000, // Connection timeout of 10 seconds
socketTimeoutMS: 30000, // Socket timeout of 30 seconds
});
3. Confirm the replica set name is correct: If you are using a replica set connection string, confirm that the replicaSet parameter matches the replica set name on the instance details page in the console.

"MongooseServerSelectionError" when connection with Mongoose is attempted

Error Message Example:
MongooseServerSelectionError: connect ECONNREFUSED 10.66.187.127:27017
Troubleshoot by following these steps:
1. Confirm the URI format is correct: In the Mongoose connection URI, both the business database and the authentication database must be specified:
// 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");
2. Confirm the Mongoose version: Mongoose version 6.x and above have removed several legacy connection parameters (such as 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,
});

ヘルプとサポート

この記事はお役に立ちましたか?

フィードバック