Search code examples
jsonnode.jsmongodbcursorbson

Nodejs Express app - Converting MongoDb Cursor to JSON


I'm running node v6.11.2, and my MongoDB is version 3.4.7. I have a MongoDB with several users registered using passportjs and express-session for sessions. For rendering things like displaynames, user preferences, etc. i'm using EJS like this:

                    <p>
                        <strong>id</strong>: <%= user._id %><br>
                        <strong>email</strong>: <%= user.local.email %><br>
                        <strong>password</strong>: <%= user.local.password %><br>
                        <strong>Display name</strong>: <%= user.info.displayname %><br>
                        <strong>Subjects</strong>: <%= user.info.subjects %><br>
                    </p>

When rendering this ejs page, the GET request references the user that is in session like this:

user: req.user

This does not work for what i'm trying to do now, as it requires the user to be logged in. I would like to have a page where i can display the registered users, including their displaynames, some of their preferences etc (like public profiles). I've tried (just for testing purposes) to slip the following line of code at the and of my app.js file:

console.log(db.users.find({}));

I expected this to return all the objects in my databse (and it does if i run it (without the console.log) in my mongo shell), but instead it returns a cursor like this:

Cursor {
  _readableState:
   ReadableState {
     objectMode: true,
     highWaterMark: 0,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: null,
     ended: false,
     endEmitted: false,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  _opts: {},
  _get: [Function: thunk] }

How do i convert this to JSON? Thanks in advance for any help.


Solution

  • I fixed it as follows: I added a few lines of code to my get request:

    User.find({}).exec(function(err, users) {
                if (err) throw err;
                res.render('mentors.ejs', {
                    'users': users
                })
    

    I was then able to access the JSON as follows:

    <% users.forEach(function (user) { %>     
        <p><%= user.info.displayname %></p>
            <p><%= user.info.subjects %></p>                                       
    <% }) %>