2015-11-12 135 views
2

第三方節點模塊,在本地主機上創建並填充mongoDB數據庫。我正在嘗試使用數據庫並從我的自定義模塊中檢索數據。即使我可以成功連接到數據庫,它也不會顯示數據庫中的集合或文檔。爲什麼我的數據庫對象的集合是空的?

我對Mongoose文檔的印象首先需要創建模式,然後爲每個我想要使用的集合創建mongoDB模型。這些模型是在第三方模塊中創建的,我想要使用的集合已經存在於數據庫中。

正如你所看到的,我對這個mongodb + mongoose + nodejs堆棧很陌生。我是否正確地在新模塊中創建模式和模型 - 這是很多代碼重複?或者我錯過了什麼?

從mongo shell我做use gtfs然後show collections確認gtfs數據庫不是空的。

> use gtfs 
switched to db gtfs 
> show collections 
agencies 
routes 
... 

然後確認有文件,在分貝爲好,

> db.routes.find({'route_id':'6182'}).pretty() 
{ 
    "_id" : ObjectId("562fcf97090e937d06a34e67"), 
    "route_id" : "6182", 
    "agency_id" : "DDOT", 
    ... 
} 

我連接到數據庫,從我的自定義模塊:

var mongoose = require('mongoose'); 
var mongo_url = 'mongodb://127.0.0.1:27017/gtfs'; 
//Each connection instance maps to a single database 
var db = mongoose.createConnection(mongo_url); 
    console.log('db -> ', db); 

我的貓鼬文檔中讀到,當你創建一個連接貓鼬引導你的連接對象打開或打開方法。所以,我知道我的問題是不創建一個數據庫連接對象,但不打開它。

當我打印出來的數據庫對象時,它顯示了收藏屬性空:

db -> { connections: 
    [ { base: [Circular], 
     collections: {}, 
     models: {}, 
     config: [Object], 
     replica: false, 
     hosts: null, 
     host: 'localhost', 
     port: 27017, 
     user: undefined, 
     pass: undefined, 
     name: 'gtfs', 
     options: [Object], 
     otherDbs: [], 
     _readyState: 2, 
     _closeCalled: false, 
     _hasOpened: false, 
     _listening: false, 
     _events: {}, 
     db: [Object] } ], 
    plugins: [], 
    models: {}, 
    modelSchemas: {}, 
    options: { pluralization: true } } 
+0

您打算只查詢數據庫中的數據,還是專門使用像Mongoose這樣的對象建模庫? – robertklep

+0

首先查詢數據,然後創建一個新的集合並將查詢結果插入文檔。我正在使用Mongoose,因爲我使用的第三方也在使用Mongoose。它只是給了我一個起點。我不知道如何在JavaScript文件中運行mongo命令。 – melis

回答

2

在我看來,這可能是更容易使用mongodb驅動程序而不是貓鼬(後者實現了一個額外的層MongoDB文檔的頂部,這很好,但通常在Mongoose填充數據庫時效果更好)。

關於如何查詢使用mongodb數據爲例(請確保在運行該腳本之前運行npm install mongodb):

var MongoClient = require('mongodb').MongoClient; 

var url = 'mongodb://localhost:27017/gtfs'; 

// Connect to the database. 
MongoClient.connect(url, function(err, db) { 

    // If an error occurred during connect, exit the script by 
    // throwing an exception. 
    if (err) throw err; 

    // Get a reference to the collection. 
    var routes = db.collection('routes'); 

    // Run a query against the `routes` collection. 
    var cursor = routes.find({ route_id : '6182' }); 

    // Read all the results from the cursor and turn them into a JS array. 
    cursor.toArray(function(err, documents) { 
    if (err) throw err; 

    // Output the results as JSON. 
    console.log('%j', documents); 

    // Close the connection. 
    db.close(); 
    }); 

}); 

插入文檔is documented here

幾乎所有節點代碼都要考慮的一件事是所有的I/O操作(網絡/數據庫/文件系統等)都是異步的,這意味着你傳遞了一個函數,當I/O操作已完成(或發生錯誤)。

這些調用不會阻止;換句話說,您只是告訴Node安排I/O操作並在完成時回覆給您。但是,在指示Node執行操作的代碼之後的任何代碼都將在執行操作後立即執行,而不僅僅在操作完成時執行。

這就是爲什麼上述嵌套代碼在函數中起作用的原因。

+0

羅伯特,非常感謝。我實際上嘗試連接MongoClient,並使用相同的代碼,直到cursor.toArray(..)。我打印出遊標對象 - 我稱之爲路線。它顯示連接:null,server:null。我認爲這是行不通的。我打算分享這是我嘗試的第二種方式,但是這個帖子太長了。我絕對不是貓鼬帶來的額外層的粉絲。再次感謝! – melis

相關問題