6

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

M2sh
  • 721
  • 11
  • 23
  • I think `Person.findOne` returns a bson file and you might want to `JSON.parse(JSON.stringify())` the document to make it an normal array object – Shih-Min Lee Sep 24 '15 at 06:27
  • Thanks, this way works too. but i think less code is better, so i want to use @qqilihq approach. – M2sh Sep 24 '15 at 06:37

2 Answers2

10

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.

Dan
  • 15
  • 6
qqilihq
  • 9,867
  • 6
  • 45
  • 81
0

Try

.findOne(...() => {})

It worked for me

Suraj Kumar
  • 5,366
  • 8
  • 19
  • 39