2016-12-16 69 views
0
// Use connect method to connect to the server 
MongoClient.connect('mongodb://localhost:27017/products', function (err, db) { 
    assert.equal(null, err); 
    console.log("Connected successfully to server"); 

    var findDocuments = function (db, callback) { 
    // Get the documents collection 
    var collection = db.collection('products'); 
    // Find some documents 
    collection.find(
     { $and: [{ 
     "qty": { 
      $gt: 0 
     } 
     }, { 
     "price": { 
      $gte: 2000.0 
     } 
     }] 
     }, 
     { "name": 1, 
     "brand": 1, 
     "_id": 0 
     }).toArray(function (err, docs) { 
     assert.equal(err, null); 
     console.log('Found docs'); 
     callback(docs); 

     db.close(); 

    }); 
    } 

}); 

function callback(docs) { 
    console.log('callback called'); 
    console.log(docs) 
} 

我只是得到Connected successfully to server,然後什麼都沒有,沒有輸出,甚至錯誤。我究竟做錯了什麼?蒙戈:找到返回任何內容沒有錯誤或者

+1

請張貼從集合中一個文檔。 –

回答

2

你缺少調用函數

findDocuments(db, callback); 

功能應該是這樣的:

MongoClient.connect('mongodb://localhost:27017/products', function (err, db) { 
assert.equal(null, err); 
console.log("Connected successfully to server"); 

var findDocuments = function (db, callback) { 
    // Get the documents collection 
    var collection = db.collection('products'); 
    // Find some documents 
    collection.find(
     { 
      $and: [{ 
       "qty": { 
        $gt: 0 
       } 
      }, { 
       "price": { 
        $gte: 2000.0 
       } 
      }] 
     }, 
     { 
      "name": 1, 
      "brand": 1, 
      "_id": 0 
     }).toArray(function (err, docs) { 
      assert.equal(err, null); 
      console.log('Found docs'); 
      callback(docs); 

      db.close(); 

     }); 
} 
findDocuments(db, callback); 

}); 
+0

Sheesh,就是這樣!我可以是多麼愚蠢。 – 3zzy

+0

發生了一些... :) –