【问题标题】:Post item with mix of objects and arrays to Mongo - the array does not post data将包含对象和数组的项目发布到 Mongo - 数组不发布数据
【发布时间】:2019-03-20 03:50:12
【问题描述】:

我正在使用 Node、Express、Mongoose 和 Vue.js 将项目发布到 Mongodb。该项目是混合对象和数组。对象 post 继承了数组 post 到 Mongo 并创建了一个 ID,但没有发布数据。

Mongoose 架构是

   const ReportSchema = Schema(
    {
        month: String,
        projects:
        [
          {
          code: String,
          name: String,
          staff: String,
          support: String
          }               // it was missing here 
        ],

API 是

app.post('/api/report/create', (req, res) => {
  const report = new Report({
    month: req.body.month,
    projects:
    [
      {
      code: req.body.projects.code,
      name: req.body.projects.name,
      staff: req.body.projects.staff,
      support: req.body.projects.support
      }
    ],

Vue.js 方法是

methods: {
    create(){
      let data = { 
        month: this.month,
        projects: [
          {
            code: this.projects.code,
            name: this.projects.name,
            staff: this.projects.staff,
            support: this.projects.supported
          }
        ],

当我在 Postman 中进行发布请求时,对象的返回是可以的,但数组没有发布数据。

"report": {
        "_id": "5c91b6d449f21705a0270732",
        "month": "January",
        "projects": [
            {
                "_id": "5c91b6d449f21705a0270733"
            }
        ],
        "__v": 0
    }

感谢任何帮助!

【问题讨论】:

  • 我猜你的架构中有一些错误“}”在项目数组中丢失
  • 您是否仍然遇到同样的问题或在编辑后解决了您的问题。

标签: node.js mongodb express vue.js mongoose


【解决方案1】:

在您的创建方法中,

let data = { 
        month: this.month,
        projects: [
          {
            code: this.projects.code,
            name: this.projects.name,
            staff: this.projects.staff,
            support: this.projects.supported
          }
        ],

您将项目作为数组发送并作为 API 中的对象访问 ---> req.body.projects.code 在您的 API 中进行以下更改,它应该可以工作。

app.post('/api/report/create', (req, res) => {
  const report = new Report({
    month: req.body.month,
    projects: req.body.projects 
})

【讨论】:

    猜你喜欢
    • 2015-12-09
    • 2012-04-11
    • 2012-05-29
    • 1970-01-01
    • 2019-10-17
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    相关资源
    最近更新 更多