【问题标题】:How to do nested loops with object jSON data on nodejs如何在nodejs上使用对象json数据进行嵌套循环
【发布时间】:2019-01-12 03:46:18
【问题描述】:

我是使用 nodejs 和 mongodb 的新手,现在我使用 nodejs 和 mongodb 构建 restful API。我想用http://jsonapi.org 标准为我的API 使用响应标准。

我需要提前建议如何最好地做到这一点,使我的 API 响应类似于以下 JSON 数据:

HTTP/1.1 200 OK
Content-Type: application/vnd.api+json

{
  "links": {
    "self": "http://example.com/users"
  },
  "data": [{
    "type": "users",
    "id": 5b647bb8998248235a0aab3c,
    "attributes": {
      "username": "luke",
      "email": "luke@mail.com",
      "password": "password",
      "hashpassword":"",
      "oldpassword":"$2a$10$eyt6YV6m2JJrebNxvS0iEuxMCubDXratNJ6/XK797IGvepXBdp9Yq",
      "salt":"2q6eN9U0vWFBsIF1MtB5WrgPiB8pldTS",
      "usertype":"bisnis",
      "userstatus":"not aktif"
    }
  }, {
    "type": "users",
    "id": 5b647bdf998248235a0aab3d,
    "attributes": {
      "username": "ken",
      "email": "ken@mail.com",
      "password": "password",
      "hashpassword":"",
      "oldpassword":"$2a$10$eyt6YV6m2JJrebNxvS0iEuxMCubDXratNJ6/XK797IGvepXBdp9Yq",
      "salt":"2q6eN9U0vWFBsIF1MtB5WrgPiB8pldTS",
      "usertype":"bisnis",
      "userstatus":"not aktif"
    }
  }]
}

如上所述创建输出时,我遇到了嵌套迭代问题。这是我的代码:

const UsersModel = mongoose.model('Users');

//...show list user
exports.listUsers = (req, res) => {
  UsersModel.find({}, (err, result) => {
    if (err) {
      res.send({code: 400, failed: 'Error 400'});
    }
    res.json(result);
  });
};

这是我的结果 JSON:

[
    {
        "type": "users",
        "userstatus": "not aktif",
        "_id": "5b647bb8998248235a0aab3c",
        "username": "luke",
        "email": "luke@mail.com",
        "password": "password",
        "usertype": "bisnis",
        "hashpassword": "$2a$10$eyt6YV6m2JJrebNxvS0iEuxMCubDXratNJ6/XK797IGvepXBdp9Yq",
        "salt": "2q6eN9U0vWFBsIF1MtB5WrgPiB8pldTS",
        "__v": 0
    },
    {
        "type": "users",
        "userstatus": "tidak aktif",
        "_id": "5b647bdf998248235a0aab3d",
        "username": "ken",
        "email": "ken@mail.com",
        "password": "password",
        "usertype": "personal",
        "hashpassword": "$2a$10$hok988mszyIBiXVNjmfifOiPNzXkBRRRynXJS/0qCkvlaBOQs65MO",
        "salt": "IiMvtVYVqTpZFXmYQIM4IlS6PJFVZ3kw",
        "__v": 0
    }
]

这是我解决问题的临时代码。

//...show list user
exports.listUsers = (req, res) => {
    UsersModel.find({}, (err, result) => {
      if (err) {
        res.send({code: 400, failed: 'Error 400'});
      }

      let listData  = [];

      for (let key in result) {
        let data = {};
        let attr = {};

        if (result.hasOwnProperty(key)) {
          data.type = result[key].type;
          data.id = result[key]._id;

          for(let i in result[key]) {

            if(result[key].hasOwnProperty(i)) {
              attr.username = result[key].username;
              attr.email = result[key].email;
              attr.password = result[key].password;
              attr.hashpassword = result[key].hashpassword;
              attr.oldpassword = result[key].oldpassword;
              attr.salt = result[key].salt;
              attr.usertype = result[key].usertype;
              attr.userstatus = result[key].userstatus;
            }
          }

          data.attribute = attr;
          listData.push(data);
        }

      }

      let collections = {
        "meta": {
          "copyright": "Copyright 2018 Kotakku Studio and Lab",
          "authors": [
            "sw. saputra"
          ]
        },
        "link": {
          "self": req.protocol + '://' + req.get('host') + req.originalUrl
        },
        "data": listData
      }

      res.json(collections);
    });
};

如果我的临时代码不正确,请给我建议优雅和最好的方法来解决我的问题。

提前感谢。

【问题讨论】:

标签: javascript json node.js mongodb express


【解决方案1】:

您需要根据您的要求创建一个合适的 mongoose 架构并将 res 映射到该架构。

//Schema for users
var UsersSchema = mongoose.Schema({
 links: {
   self: String 
 },
  data:[{
    type: String,
    attributes: {
      username: String,
      .
      .
      .
    }
  }]
})

数组中每个文档的 id 将由 MongoDB 自动创建。 对于猫鼬模式文档,请参阅http://mongoosejs.com/docs/guide.html 您也可以查看这个简单的 TODO API 以供参考https://github.com/mkujaggi/node-course-todo-api

【讨论】:

    【解决方案2】:

    在这个条件的陈述中:

    if(result[key].hasOwnProperty(i)) {
    

    您应该访问iresult[key]

            if(result[key].hasOwnProperty(i)) {
              attr.username = result[key][i].username;
              attr.email = result[key][i].email;
              attr.password = result[key][i].password;
              attr.hashpassword = result[key][i].hashpassword;
              attr.oldpassword = result[key][i].oldpassword;
              attr.salt = result[key][i].salt;
              attr.usertype = result[key][i].usertype;
              attr.userstatus = result[key][i].userstatus;
            }
    

    而且您不需要所有这些.hasOwnProperty 检查,除非您正在修改本机原型,而您可能不应该这样做。特别是对于Array,如果您只是使用for 而不是for-in 正确循环,则没有必要。

    exports.listUsers = (req, res) => {
    UsersModel.find({}, (err, result) => {
        if (err) {
          res.send({
            code: 400,
            failed: 'Error 400'
          });
        }
    
        let listData = [];
    
        let data = {};
        let attr = {};
    
        data.type = result[key].type;
        data.id = result[key]._id;
    
        for (let i = 0; i < result[key].length; i++) {
    
            attr.username = result[key][i].username;
            attr.email = result[key][i].email;
            attr.password = result[key][i].password;
            attr.hashpassword = result[key][i].hashpassword;
            attr.oldpassword = result[key][i].oldpassword;
            attr.salt = result[key][i].salt;
            attr.usertype = result[key][i].usertype;
            attr.userstatus = result[key][i].userstatus;
        }
    
        data.attribute = attr;
        listData.push(data);
      }
    
    }
    
    let collections = {
      "meta": {
        "copyright": "Copyright 2018 Kotakku Studio and Lab",
        "authors": [
          "sw. saputra"
        ]
      },
      "link": {
        "self": req.protocol + '://' + req.get('host') + req.originalUrl
      },
      "data": listData
    }
    
    res.json(collections);
    });
    };
    

    【讨论】:

    • 哦,我没有注意到数组在 JSON 响应的顶层。应该删除外循环。
    【解决方案3】:

    我会通过迭代键来做这样的事情(即使我们不知道键名,这也会动态工作)

    var test=[
        {
            "type": "users",
            "userstatus": "not aktif",
            "_id": "5b647bb8998248235a0aab3c",
            "username": "luke",
            "email": "luke@mail.com",
            "password": "password",
            "usertype": "bisnis",
            "hashpassword": "$2a$10$eyt6YV6m2JJrebNxvS0iEuxMCubDXratNJ6/XK797IGvepXBdp9Yq",
            "salt": "2q6eN9U0vWFBsIF1MtB5WrgPiB8pldTS",
            "__v": 0
        },
        {
            "type": "users",
            "userstatus": "tidak aktif",
            "_id": "5b647bdf998248235a0aab3d",
            "username": "ken",
            "email": "ken@mail.com",
            "password": "password",
            "usertype": "personal",
            "hashpassword": "$2a$10$hok988mszyIBiXVNjmfifOiPNzXkBRRRynXJS/0qCkvlaBOQs65MO",
            "salt": "IiMvtVYVqTpZFXmYQIM4IlS6PJFVZ3kw",
            "__v": 0
        }
    ]
    var listData=[]
    test.forEach((obj)=>{
       var tempObj={attributes:{}}; //initialize tempObj
       Object.keys(obj).forEach((key)=>{
         if(key=="_id" || key=="type"){
          tempObj[key]=obj[key];
         }else{
          tempObj.attributes[key]=obj[key];
          }
       })
       listData.push(tempObj);
    })
    
    let collections = {
            "meta": {
              "copyright": "Copyright 2018 Kotakku Studio and Lab",
              "authors": [
                "sw. saputra"
              ]
            },
            "link": {
              "self": 'test url'
            },
            "data": listData
          }
    console.log(collections)

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      相关资源
      最近更新 更多