Search code examples
node.jsmongodbtoarray

mongodb nodejs find toarray not showing nested object results


so i have a simple mongodb query which successfully populates results but it does not show results of the arrays of the documents. The Results are shown below and as you can see it is showing [Objects]. Please help.

MongoClient.connect(atlas, { useNewUrlParser: true }, (err, db) => {
  if (err) throw err;

  var dbo = db.db(fdb);

  dbo.collection('seturoji').find({userID: 
'x0aJqI6q9SV8yHrwYvvMS'}).toArray( (err, r1) => {
if (err) throw err;

console.log(r1)


 })

})

[ { _id: 5b2ede6ee8d8e4be9bd7142d,
userID: 'x0aJqI6q9SV8yHrwYvvMS',
sID: '2O3KlZrTgw9zA3wxEWJieYCbFuZNrrQuEoPmPVm0BsIseDVZCt',
rootFiles: { '1': [Object], '2': [Object] } },
  { _id: 5b311367e8d8e4be9bee4e50,
userID: 'x0aJqI6q9SV8yHrwYvvMS',
sID: '2O3KlZrTgw9zbFuZNrrQuEoPmPVm0BsIseDVZCt',
rootFiles: [ [Object], [Object] ] } ]

Solution

  • That's the default Node.js behaviour when it comes to displaying deep objects with console.log. You can use util.inspect to format it as console.log does, using depth: null option:

    const util = require('util');
    console.log(util.inspect(object, {depth: null}));
    

    Another option is to serialize it using JSON.stringify, especially with some formatting, like:

    console.log(JSON.stringify(object, null, 4));
    

    Which will log your serialized object, indented with 4 spaces.