node.js - 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}`);
});
解决方案
我认为问题在于您没有正确地将文档保存到集合中,因此当您检索它们时,仅显示 _id 字段。
为了能够读取请求正文,您需要将express.json()中间件添加到 server.js。
app.use(express.json());
推荐阅读
- python - 如何将自动生成的注册 ID 更改/分配给 microsoft azure 认知说话者识别 API 中的特定人员姓名
- java - 线程“main”java.lang.Error 中的异常:未解决的编译问题(Edx 课程示例)
- java - 当'e'对于非常大的e是十进制时,如何对e求幂?
- amazon-web-services - AWS SAM YAML - 多次附加相同的策略,或在相同的 DynamoDB 策略上附加多个表
- ios - 从xcode中的注释映射访问结构参数
- java - SpringBoot程序中如何为mysql动态设置sql_mode?
- mysql - 使用 phpmyadmin 运行时插入查询语法错误
- r - 使用 rstanarm 包中的 stan_aov 缺少预测变量计算贝叶斯方差分析
- android - 如何在Android中显示较小的第二个布局保持可见的主要布局?
- azure - azure b2c 和应用服务中客户端密码和重定向 URI 和应用的用途是什么