1

NOTE: I don't believe this question is a duplicate of this similar question because it is more specific.

I'm attempting to retrieve multiple objects from Mongo with the nodejs-mongodb-driver and write the objects to an HTTP response as JSON. The objects should be in the form of an array, but i don't want to call toArray() on the cursor because of the memory overhead and I try to avoid large JSON.stringify calls whenever possible.

var response = ... // an http response
collection.find().stream(JSON.stringify).pipe(response); // causes a malformed JSON string

The object in the browser appears as follow.

{"obj", "obj"}{"obj", "obj"} // clearly malformed

Is there an efficient way to do this?

1 Answer 1

2

I will explain the code you wrote so that you understand why it returns malformed JSON and why you probably need toArray() or the JSONStream libary from the answer you posted.

First collection.find() returns a Cursor object. At that point no data was read. Then, the .stream(JSON.stringify) call returns a readable Stream with the transformation function JSON.stringify. Still no data read.

The .pipe(response) call then reads the entire Stream to the end and for every object it calls the JSON.stringify function. Note that it does really call it for every single object seperately and therefore does not create an array. Instead you get your malformed JSON, object after object.

Now the answer in the question you posted as possible duplicate (Stream from a mongodb cursor to Express response in node.js) would work for you, but it requires an additional libary with a JSONStream. The JSONStream properly handles the CursorStream for JSON output. I don't know if that really reduces the overhead though, but you could try that.

Without an addition libary you will have to use toArray().

Sign up to request clarification or add additional context in comments.

2 Comments

I know why its malformed. I'm asking for an efficient way to do this. If there's an additional library why don't you suggest one.
you already posted that answer in your first line of the question. and i still think toArray is efficient. have you done tests? The library is in the answer of the question that you thought was not a duplicate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.