首页 > 解决方案 > 如何从猫鼬查找返回中删除集合名称?

问题描述

我正在尝试使用 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);

那么,如何在获取结果中摆脱这种风味(集合名称)?

标签: node.jsmongodbexpressmongooserouter

解决方案


我找到了答案。错误出现在 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);

集合名称消失。


推荐阅读