首页 > 解决方案 > Mongodb 查询不显示预期结果

问题描述

我正在使用节点和快递服务器来运行 mongoDb。对于连接和架构,我使用的是猫鼬。我成功连接数据库并能够使用邮递员发布数据,但问题是它没有显示预期的查询。Mongodb 只返回 id 而不是查询,即名称和描述

这里是模型

const mongoose = require("mongoose");
const { Schema } = mongoose;

const form = new Schema(
  {
    name: { type: String },
    description: { type: String }
  },
  {
    timestamps: true
  }
);

const formSubmit = mongoose.model("formSubmit", form);
module.exports = formSubmit;

这是我的快递服务器

const express = require("express");
const port = 5000;
const cors = require("cors");
const morgan = require("morgan");
const app = express();
const formSubmit = require("./models");
const mongoose = require("mongoose");
app.use(cors());
app.use(morgan("dev"));

mongoose
  .connect(
    "url",
    {
      useUnifiedTopology: true,
      useNewUrlParser: true
    }
  )
  .then(() => console.log("DB Connected!"))
  .catch(err => {
    console.log(err);
  });

//get method
app.get("/show", async (req, res) => {
  try {
    const entrries = await formSubmit.find();
    res.json(entrries);
  } catch (error) {
    console.log(error);
  }
});

//post method

app.post("/post", async (req, res, next) => {
  try {
    const logs = new formSubmit(req.body);
    const entry = await logs.save();
    res.json(entry);
  } catch (error) {
    if (error.name === "ValidationError") {
      res.status(422);
    }
    next(error);
  }
});

app.listen(port, () => {
  console.log(`Server is running port ${port}`);
});

标签: node.jsmongodbexpressmongoosepostman

解决方案


我认为问题在于您没有正确地将文档保存到集合中,因此当您检索它们时,仅显示 _id 字段。

为了能够读取请求正文,您需要将express.json()中间件添加到 server.js。

 app.use(express.json());

推荐阅读