Home > database >  Mongoose returns uniterable array from Schema.find({})?
Mongoose returns uniterable array from Schema.find({})?

Time:09-29

I am trying to retrieve some data from my mongo DB, and it returns all what I need, but its in some weird structure that I can't seem to get into, can't for loop through it, can't iterate with i, can't iterate through Object.entries, either!

The data:

[
  {
    _id: 666,
    username: 'VioPaige',
    email: '<email>',
    verifcode: 'noverifcode',
    confirmed: false
  },
  {
    _id: 73,
    username: 'DogeKnight',
    email: '<email>',
    verifcode: 'noverifcode',
    confirmed: true
  },
  {
    _id: 1000,
    username: 'BlockAccount',
    email: '<email>',
    verifcode: 'noverifcode',
    confirmed: true
  }
]

Is there any way I can still iterate through it?

Thanks for reading!

CodePudding user response:

You can iterate through it by using for loop as follow, where userList is the result of MongoDB Query

 for (let user of userList) {

// your opration
}

CodePudding user response:

Try chaining toArray method after find

Find({}).toArray(function(err, data) {
 console.log(data);
}

CodePudding user response:

I already had same problem.

Try to use lean option. Mongoose With Lean

const docs = await YourModel.findOne().lean();
  • Related