1

Apologies in advance for what is undoubtetly a silly question.

I'm trying to store the raw JSON documents from MongoDB inside a Node.js array. The following code gives me an atrocity of JSON inside an array, inside a string, inside an array.

let subscriptions = [];
MongoClient.connect(mongourl, function(err, db) {
    if (err) throw err;
    var dbo = db.db("sigdb");
    dbo.collection("customers").find({}).project({ _id: 0 }).toArray(function(err, result) {
    if (err) throw err;
    subscriptions.push(JSON.stringify(result));
    db.close();
    });
});

I have tried to exclude toArray(), using the syntax of findOne() - no luck. Declaring subscriptions as a standard variable only returned undefined. Not putting result through JSON.stringify() made the second part of the document appear as [Object].

Any suggestions on how to untangle this and just have JSON stored in an array would be much appreciated.

Edit: turns out that instead of subscriptions.push(result) I could just use subscriptions = result.

siaul
  • 11
  • 2
  • Likely dupe of https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – JohnnyHK Mar 09 '18 at 21:41
  • I'm not sure if the undefined variable (async) is even relevant, just thought I'd mention it anyway... – siaul Mar 09 '18 at 21:46
  • If you would provide a JSON example, would be easier to help. – calbertts Mar 09 '18 at 22:15
  • The JSON itself in the database is fine. `subscriptions` simply returns `[ '[{JSON}]' ]`, which makes sense if you look at the code, but what I want is `[{JSON}]`, which I can't find a way to get. – siaul Mar 09 '18 at 22:27
  • Why are you doing `JSON.stringify(result)` ? – calbertts Mar 09 '18 at 22:42
  • If I don't, I get `[ [ { foo: 'url', bar: [Object] } ] ]` – siaul Mar 09 '18 at 22:58
  • `connect` and `find` are both async, so putting the results in `subscriptions` doesn't really make any sense. – JohnnyHK Mar 09 '18 at 23:31
  • How do you know it's not working? `find` is asynchronous. Put a log statement inside the `toArray` call, and I bet you'll see that the data made it into `subscriptions`. If I had to guess, I'd say that the code you were using to test this failed to account for the asynchronicity. – Tom Mar 13 '18 at 00:46

0 Answers0