【问题标题】:Passing in an array of values to an express POST route将值数组传递给快速 POST 路由
【发布时间】:2017-06-07 04:44:26
【问题描述】:

我有一个名为 Todo 的猫鼬模型,它看起来像这样:

content: [{
    contentType: {
        type: String,
        default: null
    },
    contentValue: {
        type: String,
        default: null
    }
}]

我的快速 POST 路线如下所示:

app.post('/todos', authenticate, (req, res) => {
    var todo = new Todo({
        content: req.body.content

    });
    res.send(todo)
    //I am sending instead of sending the result for testing 
});

当我使用 Postman 发送 int 测试数据时,内容数组返回空“内容”:[]

我在 postman 中尝试过几种 Body 格式,包括:

{
    "content[contentType]": "reminder",
    "content[contentValue]": "Will it blend"
}

{
    "content": {
       "contentType": "reminder",
       "contentValue": "Will it blend"
    }
}

但是两者都返回空数组。

{
  "content": []
}

我是否需要更改我的 POST 路线上的某些内容并\或以其他格式发送数据?

【问题讨论】:

  • 我认为你没有调用 todo.save()

标签: arrays node.js express post mongoose


【解决方案1】:

这里的内容是一个待办事项子文档,所以你应该像下面这样对待它:

app.post('/todos', authenticate, (req, res) => {
    var content = req.body.content;
    var todo = new Todo();

    todo.content.push(content);

    todo.save(function(err) {
      if (err) throw err;
      res.json(todo.toJSON())
      //I am sending instead of sending the result for testing 
    });

});

见:Mongoose SubDocuments

【讨论】:

  • 这是正确的答案,但是作为子文档,它不会正确自动生成 ObjectID。是否需要手动生成并保存?
  • 您期待什么以及现在正在产生什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-06
  • 2018-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
相关资源
最近更新 更多