2017-09-25 66 views
0

我正在運行node v6.11.2,而我的MongoDB是3.4.7版本。 我有一個MongoDB,有幾個用戶使用passportjs和express session來註冊會話。對於渲染之類的東西displaynames,用戶偏好等我使用EJS是這樣的:Nodejs Express應用程序 - 將MongoDb光標轉換爲JSON

    <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> 

渲染此EJS頁面時,將GET請求引用舉行會議這樣的用戶:

user: req.user 

這不適合我現在要做的事情,因爲它需要用戶登錄。我想有一個頁面,我可以顯示註冊用戶,包括他們的顯示名稱,他們的一些偏好等(如公開個人資料)。 我試過(只是爲了測試目的)滑動的下面這行代碼在我的app.js文件:

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

我想到這回我DATABSE所有對象(和它如果我運行它(不執行console.log)在我蒙戈殼),而是它返回一個指針這樣的:

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] } 

我如何將它轉換爲JSON? 在此先感謝您的幫助。

回答

0

我固定它,如下所示:我添加的幾行代碼,以我的GET請求:

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

當時我能夠訪問JSON如下:

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

您可能想要在db.users.find({}).toArray()中使用toArray()方法。這會返回用戶列表而不是遊標。

+0

感謝您的回答,但我自己想清楚了。我想在問一個問題之前,我沒有充分考慮這個問題。我會回答我自己的問題。 –