代码之家  ›  专栏  ›  技术社区  ›  Aldo

如何从Mongoose查找返回中删除集合名称?

  •  0
  • Aldo  · 技术社区  · 6 年前

    我尝试使用express.js+mongoose返回node.js中mongodb集合的值。将要使用的客户机希望数据采用与我的不同的格式。返回的数据应该是这样的:

    [{ “userid”:1, “ID”:1, “title”:“部分标题”, “body”:“某个body” },{ “userid”:1, “ID”:2, “title”:“另一个标题”, “body”:“另一个正文” }…

    但是,我的服务返回的JSON的集合名(在我的示例中是flavors)是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}` });
      });
    });
    

    这里的模型/口味:

    import mongoose, { Schema } from "mongoose";
    const schema = new Schema(
    {
            name: String,
            kind: String,
     });
    
    export default mongoose.model("flavors", schema);
    

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

    1 回复  |  直到 6 年前
        1
  •  0
  •   Aldo    6 年前

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

    收藏名称消失。