Mongoose for var loop in subdocuments

I created this circuit 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 the data using the method findOne

, 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 in a subdocument socialAccounts

using a loop structure for var in

and view the data using console.log()

, it returns some other objects and a function, but only the first one is the subdocument object. How can I only get the first item of a subdirectory socialAccounts

with this for-loop iteration method.

thank

+5


source to share


2 answers


Use an indexed loop for

instead of for

... in

:

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

      



The loop for

... in

will list additional properties of the object, as you noticed, and shouldn't be used for arrays. See this question and answers.

+7


source


Try

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

      



It worked for me

0


source







All Articles