mongodb - 获取 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 被记录我得到关于数据库的信息我希望这能得到我发布的信息
解决方案
问题是您使用 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");
});
});
希望这能解决你的问题
推荐阅读
- python-3.x - 在具有不同参数的方法之间切换的字典
- jekyll - How to skip the first element in an array?
- css - 具有恒定实时链接问题的可折叠导航菜单
- c++ - How to write combinations recursively in C++
- docker - docker-compose doesn't work in specific directory
- python - AttributeError("move_to requires a WebElement") AttributeError: move_to requires a WebElement error using Action Class in Selenium Webdriver
- ios - 变量范围,斯威夫特
- c# - How can I extract values from double[,] in C#?
- mongodb - How to get element property from array in Mongoose?
- java - 抽象类如何返回子类对象的 ArrayList?