Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 248
M2sh Avatar asked Sep 24 '15 06:09

M2sh


1 Answers

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.

like image 130
qqilihq Avatar answered Sep 20 '22 16:09

qqilihq