2012-07-27 177 views
11

我正在玩弄mongodb,並在「用戶」集合中輸入了一些測試數據{name:「david」}。我驗證了數據在MongoDB中使用蒙戈外殼通過鍵入node.js MongoDB查詢不返回結果

db.users.find() 

結果:

{ "name":"david" } 

在node.js的腳本,下面的代碼:

db.open(function(err, db) { 
    if (!err) { 
     console.log("db opened!"); 
    } 
    else { 
     console.log(err); 
    } 
    db.collection('users', function(err, collection) { 
     collection.find({}, function(err, cursor) { 
      cursor.each(function(err, item) { 
       console.log(item); 
      }); 
     }); 
    }); 
    db.close(); 
}); 

不回任何結果

我沒有看到任何錯誤,沒有err返回。請告知

回答

9

你實際上關閉數據庫連接從收集的數據已返回之前。

db.collection('users', function(err, collection) { 
    collection.find({}, function(err, cursor) { 
    cursor.each(function(err, item) { 
     console.log(item); 
    }); 

    // our collection has returned, now we can close the database 
    db.close(); 
    }); 
}); 
2

此模式在我的節點/ mongo示例中正常工作。該函數傳遞一個回調函數,該函數採用err,collection。它獲取'用戶'集合,如果成功,調用將查找集合並將其轉換爲數組,但是您也可以在光標上進行迭代。

在db.collection和connection.find調用中,你沒有檢查err和處理。你只是在公開電話會議上做。

此外,如果您打開connection pool option(您不想在每次調用時打開和關閉連接),則不應該調用db.close()。如果您確實想關閉,請在回調中關閉。

喜歡的東西:

var server = new Server(host, port, {auto_reconnect: true, poolSize: 5}, {}); 

MyStore.prototype.getUsers = function(callback) { 
server.open(function(err, db) { 
    if (err) { 
     callback(err); 
    } 
    else { 
     db.collection('users', function(err, collection) { 
      if(err) 
       callback(err); 
      else { 
       collection.find().toArray(function(err, users) { 
        if (err) { 
         callback(err) 
        } else { 
         callback(null, users); 
        } 
       }); 
      } 
     } 
    }}); 

這裏的節點+蒙戈另一個教程,可以幫助:http://howtonode.org/express-mongodb

4

正如CJohn所述,您正在關閉數據庫連接,然後才能檢索數據。我知道它看起來不像,但是Node結構和回調就是這種情況。正確處理此問題的代碼是:

db.open(function(err, db) { 
    if (err) return console.log('error opening db, err = ', err); 

    console.log("db opened!"); 

    db.collection('users', function(err, collection) { 
     if (err) return console.log('error opening users collection, err = ', err); 

     collection.find({}, function(err, cursor) { 
      if (err) return console.log('error initiating find on users, err = ', err); 

      cursor.each(function(err, item) { 
       // watch for both errors and the end of the data 
       if (err || ! item) { 
        // display (or do something more interesting) with the error 
        if (err) console.log('error walking data, err = ', err); 

        // close the connection when done OR on error 
        db.close(); 

        return; 
       } 
       console.log(item); 
      }); 
     }); 
    }); 
}); 
3

嘗試將節點升級到最新版本。

sudo npm cache clean -f 
sudo npm install -g n 
sudo n stable 

版本0.4可能無法正常工作。