Mongoose for var in loop in subdocuments
Asked Answered
T

3

7

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

Turbary answered 24/9, 2015 at 6:21 Comment(2)
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 objectOestrogen
Thanks, this way works too. but i think less code is better, so i want to use @qqilihq approach.Turbary
C
12

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.

Coastline answered 24/9, 2015 at 6:25 Comment(1)
How would I enumerate over object properties with for ... in?Rosenquist
A
1

Try

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

It worked for me

Aurify answered 21/6, 2019 at 16:4 Comment(0)
D
1

Using ES6, you can iterate through the objects of array without the mess of handling the index and array access by using let obj of arr.

 for (let item of arr) {
  console.log(item)
 }
Deflagrate answered 22/11, 2022 at 18:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.