Guruprasad Rao Guruprasad Rao - 4 months ago 8
Node.js Question

collection.find({ }) does not return colelction records in nodejs

I am trying to fetch all the records from a collection using

collection.find


var DTX = mongoose.models.dtx;
var detx = DTX.find({});


But when I
console.log(detx)
, it gives me below response:

{ _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],
.....
}
.....
}
.....
}


I read few posts and then I realized that in
nodejs
this returns
cursor
. then I tried it as below:

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


This did not help either. How would I go fetching all records as
array
from collection without any condition?

Answer

Try this.

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