Search code examples
javascriptarraysnode.jsmongodbfor-in-loop

Strange behaviour "for in" statement (NodeJS)


I think I miss something into the use of "for in" statement. I have a JSON document returned from a mongoDB query (nodejs + mongoose), his structure is like the following:

  [{  
  "_id":"596f2f2ffbf8ab12bc8e5ee7",
  "date":"1500458799794",
  "questionId":4249,
  "__v":0,
  "myArray":[  
     "1234567",
     "8901234",
     "5678901"
     ]
  },
  {  
  "_id":"596f2f2ffbf8ab12bc8e5ee5",
  "date":"1500458799795",
  "questionId":4245,
  "__v":0,
  "myArray":[  
     "1234565",
     "5678905"
     ]
  }]

In a "for in" cicle I get each document and into another I want to iterate the array "myArray". The problem is when I try to iterate the array "myArray". If I iterate it with "for in" statement I receive a lot of other wrong stuff, like if I am iterating the document returned by the query:

  [null,{},{"_id":"596f2f2ffbf8ab12bc8e5ee7","date":"1500458799794","questionId":4249,"__v":0,"myArray"["1234567","8901234","5678901"]},null,null,....,"myArray",true,[],{"caster":{"enumValues":[],"regExp":null,"path":"myArray","instance":"String","validators":[],"setters":[],"getters":[],"options":{},"_index":null},"path":"whoDislikes","instance":"Array"....etc etc... ]

If I iterate it with a classic for statement everything is good: ["1234567","8901234","5678901"]

Why? The code is the following:

  for(question in data){
      var myArray=data[question].myArray;
      console.log(JSON.stringify(myArray));   //this print ["1234567","8901234","5678901"]

      for(var i=0;i<myArray.length;i++){
         console.log(myArray[i]);   //this print ["1234567","8901234","5678901"]
       }
       for(element in myArray){
          console.log(myArray[element]);   //this print a lot of wrong stuff!
       }
  }

Solution

  • Is this because Mongoose returns a Document, so the properties you are seeing are the ones further up the prototype chain.

    I think you either need the hasOwnProperty test in the for...in loop, use a classic loop, or use myArray.forEach(function (element) {});