You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Angular将LocalStorage数据存入MongoDB?字段存为null问题求助

问题排查与修复方案

核心错误:LocalStorage 键名使用错误

你在获取 LocalStorage 数据时调用了 localStorage.getItem(JSON.stringify("Users")),这会把字符串 "Users" 转换成带额外双引号的 JSON 格式字符串 '"Users"',而你存储用户名时的键应该是不带额外引号的 "Users",导致 getItem 找不到对应值,返回 null。

第一步:修正 LocalStorage 获取逻辑

直接使用原始键名 "Users" 获取数据:

// component.ts 中 ngOnInit 部分
this.myForm = this.fb.group({
  product: '',
  details: '',
  minbid: '',
  currentbid: '',
  bidno: 0,
  sellname: localStorage.getItem("Users") || '' // 替换错误的JSON.stringify调用
});

如果存储时你是把用户对象用 JSON.stringify 序列化后存入的(比如 localStorage.setItem("Users", JSON.stringify(userInfo))),需要先解析成对象再提取用户名:

ngOnInit() {
  const storedUser = localStorage.getItem("Users");
  // 替换成你实际存储的用户名属性名,比如username
  const sellname = storedUser ? JSON.parse(storedUser).username : '';

  this.myForm = this.fb.group({
    // ...其他字段
    sellname: sellname
  });
}

其他潜在问题与优化

1. 表单数值字段类型转换

minbid、currentbid 从表单获取的是字符串值,直接传给后端会导致类型不匹配,需要转成数字:

onSubmit() {
  const formData = this.myForm.value;
  this.detailsService.insertQuote(
    formData.product,
    formData.details,
    Number(formData.minbid),
    Number(formData.currentbid) || Number(formData.minbid), // 可默认将当前出价设为最低出价
    formData.bidno,
    formData.sellname
  ).subscribe(results => {
    // 替代location.reload(),避免页面强制刷新
    this.quotes.push(results);
    this.myForm.reset({ bidno: 0, sellname: localStorage.getItem("Users") || '' });
  });
}

2. 后端与数据库校验

确认你的 MongoDB 集合 Schema 中包含 sellname 字段,且后端接口没有过滤该字段。例如 Node.js + Mongoose 的 Schema 定义:

const quoteSchema = new mongoose.Schema({
  product: String,
  details: String,
  minbid: Number,
  currentbid: Number,
  bidno: Number,
  sellname: String // 必须存在该字段才能正常存储
});

3. 调试验证

打开浏览器开发者工具(F12)→ Application → LocalStorage,确认 Users 键存在且值正确;也可在 ngOnInit 中添加日志调试:

ngOnInit() {
  console.log('LocalStorage Users 值:', localStorage.getItem("Users"));
  // ...表单初始化代码
}

内容的提问来源于stack exchange,提问作者Janie Cha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 11:35:20