1

I am wanted to display every documents stored in my mongodb. I tried following code which simply get collection.find() and display through res.send()

router.get('/index', function(req,res){
var db = req.db
var collection = db.get('usercollection')

var display = util.inspect(collection.find()));
res.send(display);
});

I expected it to display the actual document stored in mongodb. But instead, it displayed this object format:

{cold:{manager:{driver:[Object], helper:[Object], collection:[Object].....

Is there any other steps needed to display raw mongodb document?

1
  • thats a MEAN stack bro Commented Dec 11, 2014 at 5:07

1 Answer 1

1

If the library you are using is the official 10gen library, then you can't simply output collection.find() without unwinding it. The easiest way to do that for smaller datasets is

collection.find().toArray(function(err, results) {
  if (err) {
      // do something error-y
  } else {
      res.send( results );
  }
});

If you post more of your code, and tag your question with the libraries you are using, you'll be able to get more targeted help. If the library you are using returns a promise, this is probably how you'd unwind it:

collection.find().then(function(results){
    res.send(results);
}).catch(function(err){
    console.error(err);
});
Sign up to request clarification or add additional context in comments.

4 Comments

I believe, you can use res.send only once per request.
Thanks! This was exactly what I tried after I explored StackOverflow. I have an error says "Object #<Promise> has no method 'toArray'. Seems toArray is not default method?
i've updated my answer to include my best guess on how you'd handle the Promise return object.
@thefourtheye, res.end() is the function you can only use once. res.send can be used as many times as you like. @Taewan should note that the response needs to be explicitly closed. Many people just use res.end( response_object ) once to send and close in one go, relieving you of having to remember close the connection

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.