[英]POST Request returns only the ID , not the data in JSON format
我正在尝试从 Postman 到 Mongo 数据库的 POST 请求。 我只获取对象的 ID,没有显示数据。
模型:
const mongoose = require("mongoose");
const categorySchema = mongoose.Schema({
name: String,
icon: String,
color: String,
});
categorySchema.virtual("id").get(function () {
return this._id.toHexString();
});
categorySchema.set("toJSON", {
virtuals: true,
});
exports.Category = mongoose.model("Category", categorySchema);
路线:
const { Category } = require("../models/category");
const express = require("express");
const router = express.Router();
router.get(`/`, async (req, res) => {
const categoryList = await Category.find();
if (!categoryList) {
res.status(500).json({ success: false });
}
res.status(200).send(categoryList);
});
router.get("/:id", async (req, res) => {
const category = await Category.findById(req.params.id);
if (!category) {
res
.status(500)
.json({ message: "The category with the given ID was not found." });
}
res.status(200).send(category);
});
router.post("/", async (req, res) => {
let category = new Category({
name: req.body.name,
icon: req.body.icon,
color: req.body.color,
});
category = await category.save();
if (!category) return res.status(400).send("the category cannot be created!");
res.send(category);
});
router.put("/:id", async (req, res) => {
const category = await Category.findByIdAndUpdate(
req.params.id,
{
name: req.body.name,
icon: req.body.icon || category.icon,
color: req.body.color,
},
{ new: true }
);
if (!category) return res.status(400).send("the category cannot be created!");
res.send(category);
});
router.delete("/:id", (req, res) => {
Category.findByIdAndRemove(req.params.id)
.then((category) => {
if (category) {
return res
.status(200)
.json({ success: true, message: "the category is deleted!" });
} else {
return res
.status(404)
.json({ success: false, message: "category not found!" });
}
})
.catch((err) => {
return res.status(500).json({ success: false, error: err });
});
});
module.exports = router;
POST 的 URL:localhost:6426/api/v1/categories?name=Srihari&icon=%23srihari&color=srihari-icon
基本 URL:localhost:6426/api/v1/categories
{
"_id": "62b58640a91799ea2bc2e1f7",
"__v": 0,
"id": "62b58640a91799ea2bc2e1f7"
}
我期望的输出是一个带有 Category 参数的 JSON 对象。
在您的代码中,您正在分配 save 方法的返回值:
router.post("/", async (req, res) => {
let category = new Category({
name: req.body.name,
icon: req.body.icon,
color: req.body.color,
});
// remove category = ...
await category.save();
if (!category) return res.status(400).send("the category cannot be created!");
res.send(category);
});
通过删除它,您应该获得所需的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.