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

Angular开发中无法将Subject以JSON格式存储到MongoDB求助

解决步骤

1. 修正Mongoose Schema定义

你当前的Schema里subject字段限制了只能存嵌套的字符串内容,且之前的存储逻辑会把内容转成字符串,不符合JSON对象存储的要求,修改如下:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SubjectSchema = new Schema({
  semesterId:{type: String,ref:'semesterNew'},
  courseId :{type: String,ref:'CollegeCourse'},
  // 若需要存储任意JSON对象,用Mixed类型;如果JSON结构固定,也可以直接定义字段结构
  // 固定结构示例:subject: {name: {type: String}, code: {type: String}}
  subject: {type: Schema.Types.Mixed, required: true},
  createdOn : {type:Date,default:Date.now},
  updatedOn : {type:Date,default:Date.now},
});

mongoose.model('Subject',SubjectSchema);

2. 修正后端接口逻辑

去掉JSON.stringify的强制转换,直接存储前端传过来的原生对象即可,新增接口修改如下:

router.post('/addSubject',function(req,res){
  var subjectData = new subjectModel({
    semesterId:req.body.semesterId,
    courseId: req.body.courseId,
    subject: req.body.subject,
  });
  subjectData.save(function (err, result) {
    if (err) {
      console.error(err);
      return res.status(400).json({
        message: 'Bad Request'
      });
    } else {
      res.json({
        status: 200,
        data: result
      })
      console.log('Check',result);
    }
  });
});

注意:你的更新接口也要同步去掉JSON.stringify转换逻辑,和新增接口保持一致

3. 修正前端提交逻辑

你现在前端将所有科目组装成了数组,需要改成组装为对象格式,示例如下(你可以根据业务需要自定义对象的键名):

saveSubject() {
  const config = {
    position: NbGlobalPhysicalPosition.BOTTOM_RIGHT
  };
  this.subjectMasterForm.controls.semesterCtrl.markAsDirty();
  this.subjectMasterForm.controls.collegeCourseCtrl.markAsDirty();

  // 将数组替换为空对象,用来存储JSON格式的科目信息
  var all_subject_obj = {};
  if (this.subjectMasterForm.valid && this.subjectMasterForm.value.subjects.length > 0) {
    if (!this.semesterSubjectId) {
      
      var subjects_values = this.subjectMasterForm.value.subjects
      // 遍历组装成对象,这里用序号作为键,你也可以换成科目自身的ID作为键
      subjects_values.forEach(function (element, index) {
        all_subject_obj[index] = element.name;
        console.log('Check2',element.name);
      });

      this.overview_data = {
        courseId: this.courseId,
        semesterId:this.semesterId,
        subject: all_subject_obj, // 传入对象而非数组
        semesterSubjectId: this.semesterSubjectId,
      }
      this.collegeTemplateApi.addSubject(this.overview_data).subscribe(data => {
        if (data['status'] == 200) {
          this.toasterService.show("科目添加成功!", `成功`, config);
        } else {
          this.toasterService.show("该科目已存在于数据库中!", `提示`, config)
        }
      });
    } else {
      if(this.courseId && this.semesterId){
        if (this.subjectMasterForm.value.subjects.length > 0) {
          var subjects_values = this.subjectMasterForm.value.subjects;
          subjects_values.forEach(function (element, index) {
            all_subject_obj[index] = element.name;
          });
          this.overview_data = {
            courseId: this.courseId,
            semesterId:this.semesterId,
            subject: all_subject_obj, // 同样传入对象
            semesterSubjectId: this.semesterSubjectId
          }
        }
        this.collegeTemplateApi.updateSubject(this.overview_data).subscribe(data => {
          if (data['status'] == 200) {
            this.toasterService.show("科目更新成功!", `成功`, config);
          } else {
            this.toasterService.show(data['message'], `提示`, config)
          }
        });
      }
    }
  } else if (this.subjectMasterForm.value.subjects.length == 0) {
    this.subjecterror = true;
  }
  setTimeout(() => this.ngOnInit(), 3000);
}

修改完成后subject字段就会以JSON对象格式存入MongoDB,如果你有特定的JSON结构要求,只需要调整前端组装对象的逻辑即可。

内容的提问来源于stack exchange,提问作者Anuj Todankar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:24:01