基于MongoDB、Angular、Node.js:获取用户用户名及商品数量
Let's walk through how to build out these two requirements using MongoDB, Node.js (with Express), and Angular. I'll break each part down with code examples you can adapt directly.
1. Get Product Count for a Specific User
This is straightforward—we just need to count how many documents in the products collection match a given userid.
MongoDB Query
You can use countDocuments() for a simple, direct count:
// Using Mongoose in Node.js const productCount = await Product.countDocuments({ userid: targetUserId });
Or with the MongoDB native driver:
const productCount = await db.collection('products').countDocuments({ userid: targetUserId });
Node.js (Express) Backend Route
Create an API endpoint to expose this functionality to your frontend:
// routes/products.js const express = require('express'); const router = express.Router(); const Product = require('../models/Product'); // Get product count for a specific user router.get('/count/:userId', async (req, res) => { try { const userId = req.params.userId; const count = await Product.countDocuments({ userid: userId }); res.status(200).json({ userId, productCount: count }); } catch (error) { res.status(500).json({ message: 'Error fetching product count', error }); } }); module.exports = router;
Angular Frontend Call
Use Angular's HttpClient to fetch the count from your API:
// product.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ProductService { private apiUrl = 'http://localhost:3000/api/products'; constructor(private http: HttpClient) {} getProductCount(userId: string): Observable<{ userId: string; productCount: number }> { return this.http.get<{ userId: string; productCount: number }>(`${this.apiUrl}/count/${userId}`); } } // In your component import { Component } from '@angular/core'; import { ProductService } from './product.service'; @Component({ selector: 'app-product-count', template: `<p>User {{ activeUserId }} has {{ productCount }} products</p>` }) export class ProductCountComponent { activeUserId = '5ab425c6f5bff145304092f7'; // Replace with dynamic user ID from auth productCount = 0; constructor(private productService: ProductService) { this.productService.getProductCount(this.activeUserId).subscribe(data => { this.productCount = data.productCount; }); } }
2. Get Usernames and Their Corresponding Product Counts
For this, we'll use MongoDB's aggregation framework to join the users and products collections, then calculate the product count per user.
MongoDB Aggregation Query
This pipeline will:
- Join
userswithproductsby matchingusers._idtoproducts.userid - Calculate the number of products per user
- Format the output to show only username and product count
// Using Mongoose const userProductCounts = await User.aggregate([ { $lookup: { from: 'products', localField: '_id', foreignField: 'userid', as: 'userProducts' } }, { $project: { _id: 0, username: 1, productCount: { $size: '$userProducts' } } } ]);
Or with the native MongoDB driver:
const userProductCounts = await db.collection('users').aggregate([ { $lookup: { from: 'products', localField: '_id', foreignField: 'userid', as: 'userProducts' } }, { $project: { _id: 0, username: 1, productCount: { $size: '$userProducts' } } } ]).toArray();
Node.js Backend Route
Add an endpoint to return this aggregated data:
// routes/users.js const express = require('express'); const router = express.Router(); const User = require('../models/User'); // Get all users with their product counts router.get('/product-counts', async (req, res) => { try { const userCounts = await User.aggregate([ { $lookup: { from: 'products', localField: '_id', foreignField: 'userid', as: 'userProducts' } }, { $project: { _id: 0, username: 1, productCount: { $size: '$userProducts' } } } ]); res.status(200).json(userCounts); } catch (error) { res.status(500).json({ message: 'Error fetching user product counts', error }); } }); module.exports = router;
Angular Frontend Display
Fetch and render the aggregated data in your component:
// user.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; interface UserProductCount { username: string; productCount: number; } @Injectable({ providedIn: 'root' }) export class UserService { private apiUrl = 'http://localhost:3000/api/users'; constructor(private http: HttpClient) {} getUserProductCounts(): Observable<UserProductCount[]> { return this.http.get<UserProductCount[]>(`${this.apiUrl}/product-counts`); } } // In your component import { Component, OnInit } from '@angular/core'; import { UserService } from './user.service'; interface UserProductCount { username: string; productCount: number; } @Component({ selector: 'app-user-product-counts', template: ` <div class="user-count-list"> <div *ngFor="let user of userCounts" class="user-count-item"> {{ user.username }}: {{ user.productCount }} {{ user.productCount === 1 ? 'product' : 'products' }} </div> </div> ` }) export class UserProductCountsComponent implements OnInit { userCounts: UserProductCount[] = []; constructor(private userService: UserService) {} ngOnInit(): void { this.userService.getUserProductCounts().subscribe(data => { this.userCounts = data; }); } }
Quick Notes
- Ensure your Mongoose models for
UserandProductmatch the collection schemas you provided. - For production, add loading states, error messages in your Angular components, and secure your API endpoints with authentication.
内容的提问来源于stack exchange,提问作者user2129896

