【问题标题】:How to remove the collection name from the mongoose find return?如何从猫鼬查找返回中删除集合名称?
【发布时间】:2019-02-17 03:17:57
【问题描述】:

我正在尝试使用 Express.js + Mongoose 在 Node.js 中返回 MongoDB 中的集合值。将要使用的客户端期望数据的格式与我的不同。返回的数据应该是这样的:

[{ “用户ID”:1, “身份证”:1, "title": "一些标题", “身体”:“一些身体” },{ “用户ID”:1, “身份证”:2, "title": "另一个标题", “身体”:“另一个身体” }, ...

但是,我的服务返回的 json 将集合名称(在我的示例中为 flavor)作为 json 中的第一个元素,如下所示:

{"flavors":[{"_id":"5b818da7fb6fc0183b40ea50","name":"a name","kind":"a kind"},{"_id":"5b818dd8fb6fc0183b40ea5b","name": "another name","kind":"another kind"},...

这是我的代码:

...
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}` });
  });
});

这里是models/flavors中的模型:

import mongoose, { Schema } from "mongoose";
const schema = new Schema(
{
        name: String,
        kind: String,
 });

export default mongoose.model("flavors", schema);

那么,我如何在 get 结果中去掉这种味道(集合名称)?

【问题讨论】:

  • 什么是 MyModel?它是有效的猫鼬模型吗?你能分享你的模型课吗
  • collection_name 是从哪里来的,为什么会出现呢?无论如何,您需要使用toObject (lean) 或toJSON 来获取 JSON 响应的干净对象。
  • 为了澄清,我添加了模型并将collection_name更改为模型的真实名称。

标签: node.js mongodb express mongoose router


【解决方案1】:

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

集合名称消失。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 2018-11-28
    • 2015-09-25
    • 2019-10-17
    • 2018-08-22
    相关资源
    最近更新 更多