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

如何通过Node.js API向MongoDB传递数组?新手技术问询

问题解决步骤

1. 确保正确接收req.body

首先,你的Express后端需要配置JSON解析中间件,这样才能正确接收前端发送的JSON格式数组数据:

// 在Express入口文件中添加
const express = require('express');
const app = express();

// 解析JSON格式的请求体
app.use(express.json());

前端发送请求时,要确保请求的Content-Type设为application/json,并以JSON格式传递数据,这样req.body就能直接拿到前端传来的operatingSystems、databases等数组字段。

2. 修正MongoDB Schema关联(关键)

你的ExperienceSchema定义没问题,但需要确保CV的Schema里包含techExperiences数组,且数组元素类型为ExperienceSchema,否则无法正确嵌入子文档:

const mongoose = require('mongoose');
const { Schema } = mongoose;

// 你的ExperienceSchema
const ExperienceSchema = Schema({
  operatingSystems: { type: Array, default: [] },
  databases: { type: Array, default: [] },
  integrations: { type: Array, default: [] },
  frameworks: { type: Array, default: [] },
  otherTechnicalSkills: { type: String, required: false },
  description: { type: String, required: false, maxLength: 50 }
});

// CV Schema需要包含techExperiences数组
const CVSchema = Schema({
  // 这里添加CV的其他字段,比如name、email等
  techExperiences: [ExperienceSchema] // 嵌入ExperienceSchema作为数组元素
});

// 创建CV模型
const CV = mongoose.model('CV', CVSchema);
module.exports = CV;

3. 修正控制器代码中的错误

你的控制器里存在多个问题,以下是修正后的完整代码:

export const addExperience = async(req, res) => {
  try {
    const id = req.params.cvId;
    const filter = { _id: id };
    
    // 构造要添加的techExperience对象
    const newTechExperience = {
      operatingSystems: req.body.operatingSystems,
      databases: req.body.databases,
      integrations: req.body.integrations,
      frameworks: req.body.frameworks, // 修正拼写错误:framework -> frameworks
      otherTechnicalSkills: req.body.otherTechnicalSkills,
      description: req.body.description
    };

    // 正确的$push用法:添加单个子文档到techExperiences数组
    const update = { 
      $push: {
        techExperiences: newTechExperience
      }
    };

    const opts = { new: true }; // 返回更新后的文档
    let cv = await CV.findOneAndUpdate(filter, update, opts);

    res.status(200).send(cv);
  } catch (error) {
    res.status(500).send(error);
  }
};

控制器错误说明:

  • 删除了无用的const operatingSystemArray = req.operatingSystems.array.split(',');:前端已经传递了数组,不需要拆分字符串。
  • 修正了拼写错误:framework改为frameworks,和Schema、前端字段保持一致。
  • 修正了$push的$each用法:$each用于批量添加多个元素,如果你只是添加单个技术经验条目,直接传递对象即可;如果需要批量添加,才用$each包裹数组,示例如下:
// 批量添加多个技术经验的写法
const update = { 
  $push: {
    techExperiences: {
      $each: [
        // 多个techExperience对象,比如从req.body.items数组获取
        req.body.items[0],
        req.body.items[1]
      ]
    }
  }
};

4. 测试验证

发送POST请求时,请求体示例如下(JSON格式):

{
  "operatingSystems": ["RHEL Linux", "Fedora Linux", "CentOs Linux", "Debian Linux"],
  "databases": ["Oracle RDBMS", "Oracle DB BM DB2", "Microsoft SQL Server"],
  "integrations": ["Data", "COBRA", "Power"],
  "frameworks": ["Angular", "Ember.js", "Node.js"],
  "otherTechnicalSkills": "额外技能",
  "description": "技能描述"
}

内容的提问来源于stack exchange,提问作者GRACE KABERERE

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:18:39