首页 > 解决方案 > 获取 JSON 不返回发布的对象

问题描述

我正在向 Mongo 发布一个对象并得到它,但它没有返回我发布的内容。我是后端新手,无法弄清楚发生了什么代码都没有错误,所以也许它与服务器有关?我没有收到任何我要成功添加的错误

http://localhost:4000/todos/add
Post
{
      "todo_description": "My First Todo",
      "todo_responsible": "Sebastian",
      "todo_priority": "Medium",
      "todo_completed": false
}

get http://localhost:4000/todos

[
    {
        "_id": "5d19426d5c6af41120abab1f",
        "__v": 0
    }
]

//this is the function that adds the todo item
todoRoutes.route("/add").post(function(req, res) {
  let todo = new Todo(req.body);
  todo.save()
    .then(todo => {
      res.status(200).json(todo);
    })
    .catch(err => {
      res.status(400).send("adding new todo failed");
    });
});

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let Todo = new Schema({
  todo_description: {
    type: String
  },
  todo_responsible: {
    type: String
  },
  todo_priority: {
    type: String
  },
  todo_completed: {
    type: Boolean
  }
});

module.exports = mongoose.model("Todo", Todo);

todo 被记录我得到关于数据库的信息我希望这能得到我发布的信息

标签: mongodbhttprequestpostmanbackend

解决方案


问题是您使用 value 制作自己的 JSON 对象"todo added successfully"。如果要返回新创建的 todo 对象,请使用以下代码,

todoRoutes.route("/add").post(function(req, res) {
let todo = new Todo(req.body);
todo.save()
  .then(todo => {
    res.status(200).json(todo); // <--- change to this
  })
  .catch(err => {
    res.status(400).send("adding new todo failed");
  });
});

希望这能解决你的问题


推荐阅读