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

Why is the collections empty of my database object?

本文关键字:集合 对象 我的 数据库 为什么      更新时间:2023-09-26

第三方节点模块,在localhost上创建并填充mongoDB数据库。我正在尝试使用数据库并从我的自定义模块中检索数据。尽管我可以成功连接到数据库,但数据库中没有显示任何集合或文档。

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

正如您所知,我是mongodb+mongose+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);

我在mongoose文档中读到,当您创建连接时,mongoose会将您的连接对象指向open或openSet方法。所以,我知道我的问题不是创建一个数据库连接对象,而是不打开它

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

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

此处记录了插入文档的过程。

几乎任何Node代码都需要考虑的一件事是,所有I/O操作(网络/数据库/文件系统等)都是异步的,这意味着您传递了一个函数,该函数将在I/O操作完成(或发生错误)时调用。

这些呼叫不会阻塞;换句话说,您只是告诉Node安排一个I/O操作,并在操作完成后返回给您。但是,在您告诉Node执行操作的代码之后的任何代码都将立即执行,而不仅仅是在操作完成时执行。

这就是上面代码将函数嵌套在函数中的原因。