node.js - 如何从猫鼬查找返回中删除集合名称?
问题描述
我正在尝试使用 Express.js + Mongoose 在 Node.js 中返回 MongoDB 中的集合的值。将要使用的客户端期望数据的格式与我的不同。返回的数据应该是这样的:
[{ "userId": 1, "id": 1, "title": "some title", "body": "some body" },{ "userId": 1, "id": 2, "title": “另一个标题”,“正文”:“另一个正文”},...
但是,我的服务返回的 json 将集合名称(在我的示例中,flavors)作为 json 中的第一个元素,如下所示:
{"flavors":[{"_id":"5b818da7fb6fc0183b40ea50","name":"a name","kind":"a kind"},{"_id":"5b818dd8fb6fc0183b40ea5b","name":"另一个名字","种类":"另一种"},...
那是我的代码:
...
import Flavor from "../models/flavors";
...
const router = express.Router();
router.options("/", (req, res) => {
Flavor.find().then(result => {
res.json({ result });
}).catch((err) => {
res.status(500).json({ success: false, msg: `Something went wrong. ${err}` });
});
});
这里是模型/口味中的模型:
import mongoose, { Schema } from "mongoose";
const schema = new Schema(
{
name: String,
kind: String,
});
export default mongoose.model("flavors", schema);
那么,如何在获取结果中摆脱这种风味(集合名称)?
解决方案
我找到了答案。错误出现在 res.json 中的花括号中,在这部分代码中:
router.options("/", (req, res) => {
Flavor.find().then(result => {
res.json({ result });
}).catch((err) => {
res.status(500).json({ success: false, msg: `Something wrong. ${err}` });});});`
因此,如果以这种方式使用它:
res.json({ result });
来自 mongo/mongoose 的集合名称将首先显示。当我改变这种方式时:
res.json(result);
集合名称消失。
推荐阅读
- flutter - 未处理的异常:NoSuchMethodError:在 null 上调用了 getter 'id'。在颤振中
- ios - 如何限制字符数,同时只允许 TextField 中的字符子集?
- node.js - 如何设置节点 http 代理来拦截特定的请求/响应?
- python - 更改颜色是基于数据库中列的表格单元格
- devops - 无法重新加载 Prometheus 配置
- javascript - 如何在 React 功能组件中正确设置 setInterval 计时器?
- python - 尽管有 GIL,多线程仍可加速 CPU 密集型任务
- python - 如何在 Python 中读取 .xz 文件?
- ios - 在应用存档时在 Realm 中收到警告
- sql - 我的 .Include 语句执行 INNER JOIN 而不是 LEFT JOIN (EF Core 3.1)