为什么我的数据库对象的集合是空的?

第三方节点模块,在本地主机上创build并填充mongoDB数据库。 我正在尝试使用数据库,并从我的自定义模块中检索数据。 即使我可以成功连接到数据库,它也不会显示数据库中的集合或文档。

我从Mongoose文档中得到的印象,首先我要创build模式,然后为每个我想要使用的集合创buildmongoDB的模型。 这些模型是在第三方模块中创build的,我想要使用的集合已经存在于数据库中。

如你所知,我对这个mongodb + mongoose + nodejs栈是新手。 我是否正确地在新模块中创build模式和模型 – 这是很多代码重复?或者我错过了什么?

从mongo shell我use gtfs然后show collections来确认gtfs数据库不是空的。

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

然后确认在db中也有文件,

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

我在mongoose的文档中读到,当你创build一个连接mongoose引导你的连接对象要么打开或openSet方法。 所以,我知道我的问题是不创build一个数据库连接对象,但不打开它。

当我打印出数据库对象时,它显示集合属性为空:

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

在我看来,使用mongodb驱动程序而不是Mongoose可能更容易(后者在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(); }); }); 

在这里logging插入文件 。

有一点需要考虑的是,所有的I / O操作(networking/数据库/文件系统等)都是asynchronous的,这意味着你传递了一个函数,当I / O操作完成时,或发生错误)。

这些电话不会阻止; 换句话说,您只是告诉节点安排一个I / O操作,并在完成时回复给您。 但是,在指示节点执行操作的代码之后的任何代码都将在执行后立即执行,而不是在操作完成时执行。

这就是为什么上述嵌套代码在函数中起作用的原因。