0

I'm stuck at reading out nested JSON elements that were saved in a MongoDB. I'm trying it with the following method:

blockChainModel.find({"transactions.user": "eltaieyo"}, null, {projection : { transactions: {user : 1}} }, (err, blocks) => {
            if (err) console.error("Cannot find the specified Blocks");
            console.log(blocks);
});

The JSON in the MongoDB, that I'm trying to read looks like this: JSON Image

I want to read out the "transactions" section, and this is what the current method in my Code does: OUTPUT Image

Maybe It is reading them out but my method doesn't give them out correctly?

younes.xd
  • 11
  • 1
  • 8
  • The projection should be the 2nd param not the 3rd and also without the projection key `{ transactions: {user : 1}}` but first you should try without the projection. Check this playground https://mongoplayground.net/p/4DriEYeOzD- – Molda Oct 07 '21 at 07:14
  • @Molda I did that, thank you. It is returning all the data, expect for the nested data which is in the transactions array. That's the data that I need but it is giving it out like this: transactions : [ [Object], [Object], [Object] ] – younes.xd Oct 07 '21 at 07:29
  • The reason you see `[Object]` is just the way console.log works, i believe it only shows data 2 levels deep. To see the full data use either `console.log(JSON.stringify(blocks))` or `console.log(require('util').inspect(blocks))` – Molda Oct 07 '21 at 12:08

1 Answers1

0

How about remove projection and try again to check if there is actually some data return ?

YuTing
  • 6,555
  • 2
  • 6
  • 16
  • Data is being returned, the whole transaction is being returned but the necessary infos that are being stored in the "transactions" part is just put out like this: transactions: [ [Object], [Object], [Object] ] – younes.xd Oct 07 '21 at 07:19
  • Are you using `console.log()` to check the value, if so, you may need `JSON.stringify()` to reveal the [object] – YuTing Oct 07 '21 at 08:35
  • Currently I'm using console.log() to give the transaction out. I'm just doing a blockChain prototype that will be used in a bigger project afterwards that's why i'm just using console.log() to check if everything works. If I do JSON.stringify(blocks), it does the same thing as before. Maybe I'm using it wrong – younes.xd Oct 07 '21 at 08:41
  • I think the data is fine, it actually return what you what in the variable. – YuTing Oct 07 '21 at 08:45
  • Thanks for your help and time. It now gives the data out how i want it. Have a nice day ;) – younes.xd Oct 07 '21 at 08:47