Search code examples
node.jsmongodbfor-loopmongoosesubdocument

Mongoose for var in loop in subdocuments


I created this schema with mongoose Schema :

socialAccount =  new Schema({
    socialNetwork : { type : String , required : true},
    userid : { type : Number,  required :  true },
    username : String
},{_id : false});
person = new Schema({
    id : { type : Number,  unique : true, required : true , dropDups :  true },
    firstname : String,
    lastname : String,
    socialAccounts : [socialAccount],
    updated : { type : Date, default : Date.now },
    enable : { type : Boolean , default : true },       
});

When i get data with findOne method the result looks like this (in console.log()) :

{ 
  id: 1,
  firstname: 'example name',
  lastname: 'example last',
  enable: true,
  updated: Thu Sep 24 2015 09:40:17 GMT+0330 (IRST),
  socialAccounts: 
   [ { socialNetwork: 'instagram',
       userid: 1234567,
       username: 'example' } ] }

SO, When i want to iterate on subdocument socialAccounts with for var in loop structure & view data with console.log(), it returns some other objects & function & only the first one is subdocument object.
How can i get only first element of socialAccounts subdocument with this for-loop iterate method.

Thanks


Solution

  • Use an indexed for loop, instead of a forin:

    for (let i = 0; i < socialAccounts.length; i++) {
        var currentAccount = socialAccounts[i];
    }
    

    The forin loop will enumerate additional object properties as you noticed and should not be used for arrays. See this question and answers.