collection.find({})不返回nodejs中的集合记录

时间:2016-07-14 12:12:29

标签: node.js mongodb mongoose

我正在尝试使用collection.find

从集合中获取所有记录
var DTX = mongoose.models.dtx;
var detx = DTX.find({});

但是当我console.log(detx)时,它会给我以下回复:

{ _mongooseOptions: {},
  mongooseCollection: 
   { collection: 
      { db: [Object],
        collectionName: 'dtx',
        internalHint: null,
        opts: {},
        slaveOk: false,
        serializeFunctions: false,
        raw: false,
        pkFactory: [Object],
        serverCapabilities: undefined },
     opts: { bufferCommands: true, capped: false },
     name: 'ddtx',
     conn: 
      { base: [Object],
        collections: [Object],
        models: [Object],
        replica: false,
        hosts: null,
        host: 'localhost',
        port: 27017,
        user: undefined,
        pass: undefined,
        name: 't23',
        options: [Object],
        otherDbs: [],
        _readyState: 1,
        _closeCalled: false,
        _hasOpened: true,
        _listening: true,
        _events: [Object],
        db: [Object] },
     queue: [],
     buffer: false },
  model: 
   { [Function: model]
     base: 
      { connections: [Object],
        plugins: [],
        models: [Object],
        modelSchemas: [Object],
        options: [Object],
        dbConnected: true },
     modelName: 'dtx',
     model: [Function: model],
     .....
    }
     .....  
   }
     .....
}

我阅读了几篇帖子,然后我意识到在nodejs中,这会返回cursor。然后我尝试了如下:

var detx=DTX.find({},function(err,cursor){
            cursor.each(err,item){
              return item;
            });
         });

这也无济于事。如何在没有任何条件的情况下从集合中获取所有记录为array

1 个答案:

答案 0 :(得分:1)

试试这个。

var DTX = mongoose.models.dtx;
var detx = [];
DTX.find({})
   .exec(function (err, dtxArray) {

      if (err) 
         console.log(err);

      console.log('DTX Array: ', dtxArray);

      detx = dtxArray;
});