如何通过Angular从MongoDB查询指定用户的投标产品
问题分析与修复方案
你的代码核心问题在于后端API错误地将字符串类型的bidname当作MongoDB的ObjectId来查询,导致无法匹配到正确的投标记录。以下是具体修复步骤:
1. 修复后端API(api.js)
原代码中使用ObjectId(req.params.bidname)匹配bidname字段,但你的bidname是普通字符串(如"June"),并非MongoDB的ObjectId类型。直接用参数值匹配即可,同时需要将查询游标转为数组返回:
router.get('/quotes/:bidname', (req, res) => { db.collection('carDetails').find({"bidname": req.params.bidname}) .toArray((err, results) => { if (err) { console.error(err); return res.status(500).send('查询失败'); } res.send(results); }); });
2. 优化前端组件逻辑(component.ts)
将数据请求移到ngOnInit生命周期钩子中,并处理localStorage.getItem("username")可能返回null的情况:
export class DisplaybidsComponent implements OnInit { title = 'Product Details'; quotes: any[] = []; constructor(private rentService: RentserviceService) { } ngOnInit(): void { const bidname = localStorage.getItem("username"); if (bidname) { this.rentService.getNamePost(bidname).subscribe({ next: (quotes) => { this.quotes = quotes; }, error: (err) => { console.error('获取投标记录失败:', err); } }); } else { console.log('未找到本地存储的用户名'); } } }
3. 修正前端HTML结构
移除多余的</form>标签,避免DOM结构错误:
<div style="text-align:center"> <h1 style="font-family:monospace;"> {{title}} </h1> </div> <div class="two"> <div class="row" *ngFor="let quote of quotes" style="font-family:monospace;" class="city"> <div class="card card-body"> <h2 class="card-title">产品名称: {{ quote.product }}</h2> <h2 class="card-text">详情: {{ quote.details}}</h2> <h2 class="card-text">当前投标价: {{ quote.currentbid}}</h2> </div> </div> </div>
额外注意事项
- 确保后端配置了正确的跨域(CORS)规则,避免前端请求被拦截
- 检查MongoDB集合
carDetails中的bidname字段值与localStorage中的username完全一致(区分大小写)
内容的提问来源于stack exchange,提问作者Janie Cha
相关产品推荐
相关产品推荐

