Skip to content

implemented db setup using mongodb and mongoose#6

Merged
ravixalgorithm merged 1 commit into
Open-Dev-Society:mainfrom
ravixalgorithm:database
Oct 2, 2025
Merged

implemented db setup using mongodb and mongoose#6
ravixalgorithm merged 1 commit into
Open-Dev-Society:mainfrom
ravixalgorithm:database

Conversation

@ravixalgorithm

@ravixalgorithm ravixalgorithm commented Oct 2, 2025

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Added visible titles to market widgets: “Market Quotes” and “Top Stories” for clearer section labeling.
  • Chores

    • Integrated database connectivity support and related configuration to prepare the app for persistent data features.
    • Updated dependencies to include database tooling.
  • Tests

    • Added scripts to verify database connectivity, providing quick feedback on environment setup and connection health.

@coderabbitai

coderabbitai Bot commented Oct 2, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Adds titles to two TradingViewWidget instances in the root page. Introduces a MongoDB connection utility with cached singleton behavior. Adds database dependencies and a test script entry. Provides two DB connectivity test scripts: a Node mjs script using dotenv/mongoose and a TS script using the shared connection utility.

Changes

Cohort / File(s) Summary of changes
UI: TradingView titles
app/(root)/page.tsx
Added title props "Market Quotes" and "Top Stories" to two TradingViewWidget instances; minor whitespace adjustments.
DB: Mongoose connection utility
database/mongoose.ts
New singleton-style MongoDB connector using mongoose; caches connection and in-flight promise via a global augmentation; reads MONGODB_URI; exports connectToDatabase().
Tooling: DB test scripts
scripts/test-db.mjs, scripts/test-db.ts
New scripts to validate DB connectivity. mjs loads dotenv and connects via mongoose directly; TS uses connectToDatabase utility; both log results and set exit codes.
Config: Package updates
package.json
Added dependencies: dotenv, mongodb, mongoose. Added script: "test:db" for DB testing.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as Dev/Server
  participant Env as Env (MONGODB_URI)
  participant DBUtil as connectToDatabase()
  participant Mongoose as mongoose
  Note over DBUtil: On call, reuse cached connection or in-flight promise if present
  Dev->>DBUtil: connectToDatabase()
  DBUtil->>Env: Read MONGODB_URI
  alt Missing URI
    DBUtil-->>Dev: Throw error
  else Cached connection
    DBUtil-->>Dev: Return cached mongoose instance
  else In-flight promise
    DBUtil-->>Dev: Await and return resolved instance
  else No cache
    DBUtil->>Mongoose: mongoose.connect(MONGODB_URI, opts)
    Mongoose-->>DBUtil: Connected mongoose
    DBUtil->>DBUtil: Cache connection & promise
    DBUtil-->>Dev: Return mongoose
  end
Loading
sequenceDiagram
  autonumber
  actor CLI as CLI
  participant dotenv as dotenv
  participant Mongoose as mongoose
  participant Env as Env (MONGODB_URI)
  Note over CLI: scripts/test-db.mjs
  CLI->>dotenv: config()
  CLI->>Env: Read MONGODB_URI
  alt Missing URI
    CLI-->>CLI: Log error
    CLI-->>CLI: process.exit(1)
  else Present
    CLI->>Mongoose: connect(MONGODB_URI, { bufferCommands: false })
    Mongoose-->>CLI: Connection
    CLI-->>CLI: Log DB name/host, elapsed
    CLI->>Mongoose: connection.close()
    CLI-->>CLI: process.exit(0)
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

I nibbled wires, soft and sly,
Titled charts beneath the sky.
Burrowed deep where Mongo hums,
Cached a tunnel — no double runs.
Scripts go hop, connect, then cheer,
Carrots logged: “DB’s clear!” 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly summarizes the primary change by stating that the pull request implements database setup using MongoDB and Mongoose, which aligns with the added connection utility, dependencies, and test scripts in the changeset.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (4)
package.json (1)

10-10: Clarify the relationship between test-db.mjs and test-db.ts.

The test:db script references scripts/test-db.mjs, but there's also a scripts/test-db.ts file in this PR. Consider documenting why both exist or consolidating if one is redundant.

database/mongoose.ts (1)

1-3: Add validation and type annotation.

The connection utility reads MONGODB_URI at module load time. Consider:

  1. Adding explicit return type annotation to connectToDatabase for better type safety
  2. The current approach reads the env var once at import time, which is fine for most scenarios

Apply this diff:

-export const connectToDatabase = async () => {
+export const connectToDatabase = async (): Promise<typeof mongoose> => {
scripts/test-db.mjs (2)

1-30: Consider using the shared connection utility.

This script directly connects via mongoose.connect instead of using the connectToDatabase utility from database/mongoose.ts. This creates inconsistency and bypasses the singleton pattern established for the application.

Consider either:

  1. Using the shared utility (requires converting this script to use the utility or making the utility work in this context)
  2. Documenting why this test script intentionally bypasses the utility (e.g., to test raw connection without caching)

If keeping the direct connection approach, ensure this divergence is intentional and documented.


25-25: Silent error suppression in cleanup.

The empty catch block on line 25 silently suppresses any errors during connection cleanup. While this is often acceptable for cleanup in error paths, it makes debugging connection issues harder.

Consider logging suppressed errors:

-        try { await mongoose.connection.close(); } catch {}
+        try { await mongoose.connection.close(); } catch (closeErr) {
+            console.error('Warning: Failed to close connection:', closeErr);
+        }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ad0a0cb and d67b3c5.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • app/(root)/page.tsx (1 hunks)
  • database/mongoose.ts (1 hunks)
  • package.json (2 hunks)
  • scripts/test-db.mjs (1 hunks)
  • scripts/test-db.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
scripts/test-db.ts (1)
database/mongoose.ts (1)
  • connectToDatabase (18-38)
app/(root)/page.tsx (1)
lib/constants.ts (1)
  • MARKET_DATA_WIDGET_CONFIG (128-171)
🔇 Additional comments (8)
app/(root)/page.tsx (1)

33-33: Title additions improve consistency.

Adding title props to these TradingViewWidget instances aligns with the existing pattern used for other widgets in the file (lines 12, 22), improving UI consistency.

Note: These changes appear unrelated to the PR's stated objective of implementing database setup with MongoDB and mongoose.

Also applies to: 41-41

database/mongoose.ts (2)

5-10: Global cache pattern is appropriate for Next.js.

The global cache with type augmentation is a correct pattern for preventing connection pool exhaustion in Next.js development (hot reload) and serverless environments. This aligns with mongoose best practices for Next.js applications.

Based on learnings.


26-26: Confirm intentional use of bufferCommands: false – Disables Mongoose’s operation buffering so any CRUD calls when the DB is disconnected will error immediately rather than queue. Appropriate for request/response workloads (e.g. serverless functions, health checks) but risks surfacing errors on transient disconnects. If you proceed, disable schema autoCreate or manually call createCollection, and consider tuning driver‐level timeouts (serverSelectionTimeoutMS) or using bufferTimeoutMS for limited buffering.

scripts/test-db.ts (1)

1-16: Test script is well-structured.

The test script correctly:

  • Imports the connection utility
  • Handles success and error cases with appropriate exit codes
  • Provides clear logging

However, note:

  1. The underlying connectToDatabase function has critical issues (missing return statement, credential logging) that should be fixed first
  2. This TypeScript version appears unused since package.json references test-db.mjs
scripts/test-db.mjs (2)

11-21: Good: Timing and connection details logging.

The script appropriately measures connection time and extracts useful debugging information (database name, host) with safe fallbacks to "(unknown)". The explicit connection closure is also correct.


16-19: No credential exposure in host logging
mongoose.connection.host returns only the hostname (and port, if present); credentials are stored separately and not included in this value.

package.json (2)

24-27: mongoose@8.19.0 and mongodb@6.20.0 are up-to-date and include all known security patches


9-9: No changes required for lint script
ESLint v9 CLI lints all matching files by default and automatically loads eslint.config.mjs.

Comment thread database/mongoose.ts
Comment on lines +18 to +38
export const connectToDatabase = async () => {
if(!MONGODB_URI){
throw new Error("MongoDB URI is missing");
}

if(cached.conn) return cached.conn;

if(!cached.promise) {
cached.promise = mongoose.connect(MONGODB_URI, {bufferCommands: false});
}

try{
cached.conn = await cached.promise;
}
catch(err){
cached.promise = null;
throw err;
}

console.log(`MongoDB Connected ${MONGODB_URI} in ${process.env.NODE_ENV}`);
} No newline at end of file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Missing return statement causes type error.

The function signature on line 18 and the conditional return on line 23 imply that connectToDatabase should return typeof mongoose. However, line 37 doesn't return anything after successfully establishing a connection, causing a type mismatch.

Apply this diff:

     console.log(`MongoDB Connected ${MONGODB_URI} in ${process.env.NODE_ENV}`);
+    return cached.conn;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const connectToDatabase = async () => {
if(!MONGODB_URI){
throw new Error("MongoDB URI is missing");
}
if(cached.conn) return cached.conn;
if(!cached.promise) {
cached.promise = mongoose.connect(MONGODB_URI, {bufferCommands: false});
}
try{
cached.conn = await cached.promise;
}
catch(err){
cached.promise = null;
throw err;
}
console.log(`MongoDB Connected ${MONGODB_URI} in ${process.env.NODE_ENV}`);
}
export const connectToDatabase = async () => {
if(!MONGODB_URI){
throw new Error("MongoDB URI is missing");
}
if(cached.conn) return cached.conn;
if(!cached.promise) {
cached.promise = mongoose.connect(MONGODB_URI, {bufferCommands: false});
}
try{
cached.conn = await cached.promise;
}
catch(err){
cached.promise = null;
throw err;
}
console.log(`MongoDB Connected ${MONGODB_URI} in ${process.env.NODE_ENV}`);
return cached.conn;
}
🤖 Prompt for AI Agents
In database/mongoose.ts around lines 18 to 38, the function establishes a
connection but never returns the connection on success, causing a type error;
after setting cached.conn and logging the success, return cached.conn (ensuring
the function returns the mongoose connection type), and keep the existing early
return on cached.conn and the error handling that resets cached.promise.

Comment thread database/mongoose.ts
throw err;
}

console.log(`MongoDB Connected ${MONGODB_URI} in ${process.env.NODE_ENV}`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: Logging MONGODB_URI exposes credentials.

Line 37 logs the full MONGODB_URI, which typically contains sensitive credentials (username, password, connection string). This creates a security risk as credentials may appear in application logs, CloudWatch, or other log aggregation systems.

Apply this diff to log safely:

-    console.log(`MongoDB Connected ${MONGODB_URI} in ${process.env.NODE_ENV}`);
+    console.log(`MongoDB Connected successfully in ${process.env.NODE_ENV}`);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.log(`MongoDB Connected ${MONGODB_URI} in ${process.env.NODE_ENV}`);
console.log(`MongoDB Connected successfully in ${process.env.NODE_ENV}`);
🤖 Prompt for AI Agents
In database/mongoose.ts around line 37, the current console.log prints the full
MONGODB_URI which may contain credentials; remove any direct logging of
process.env.MONGODB_URI and instead log a safe message (e.g., "MongoDB
connected" plus environment) or parse the URI and log only non-sensitive parts
(host(s) and database name) after redacting userinfo; update the log call to
avoid exposing username/password and ensure no other code prints the raw
MONGODB_URI.

@ravixalgorithm ravixalgorithm merged commit cc7e86d into Open-Dev-Society:main Oct 2, 2025
1 check passed
afanty2021 added a commit to afanty2021/OpenStock that referenced this pull request Feb 24, 2026
修复 Critical Open-Dev-Society#1, Important Open-Dev-Society#4 和 建议 Open-Dev-Society#6 代码质量问题:

1. 修复价格轮询 useEffect 依赖项问题 (Critical Open-Dev-Society#1)
   - 使用 useRef 存储 stocks 引用,避免依赖 stocks 导致 interval 重新创建
   - 改为依赖 stocks.length 而非整个 stocks 对象
   - 防止内存泄漏和性能问题

2. 改进类型安全性 (Important Open-Dev-Society#4)
   - 将 data 属性从 any[] 改为 WatchlistStockInput[]
   - 导出 WatchlistStock 和 WatchlistStockInput 类型供其他模块使用
   - 使用 ?? 替代 || 进行空值合并,更符合 TypeScript 最佳实践

3. 提取魔法数字为常量 (建议 Open-Dev-Society#6)
   - PRICE_POLLING_INTERVAL: 价格轮询间隔 (5000ms)
   - TURNOVER_RATE_HIGH_THRESHOLD: 换手率高阈值 (10%)
   - TURNOVER_RATE_MEDIUM_THRESHOLD: 换手率中阈值 (5%)
   - VOLUME_UNIT_WAN: 成交量单位-万 (10000)
   - VOLUME_UNIT_YI: 成交量单位-亿 (100000000)

4. 其他改进
   - 使用 useCallback 优化辅助函数性能
   - 添加更详细的类型注释

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant