Related
This question already has answers here:
nodejs get find results in mongodb
(2 answers)
Closed 3 years ago.
Trying to fetch data from MongoDB to Node JS
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Mydb");
console.log("Hello")
dbo.collection("POC_DB").find({}, function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
If I make it as "result.name" then I am getting output as undefined.
I am suspecting that it could be the value in raw parameter given in the actual output.
Actual Cursor Output
Cursor {
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
emitClose: true,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
operation:
FindOperation {
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [ReadPreference],
db: [Db],
promiseLibrary: [Function: Promise] },
ns: MongoDBNamespace { db: 'Mydb', collection: 'POC_DB' },
cmd:
{ find: 'Mydb.POC_DB',
limit: 0,
skip: 0,
query: {},
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [ReadPreference] },
readPreference: ReadPreference { mode: 'primary', tags: undefined },
cursorState:
{ cursorId: null,
cmd: [Object],
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined,
reconnect: true } },
pool: null,
server: null,
disconnectHandler: undefined,
bson: undefined,
ns: 'Mydb.POC_DB',
namespace: MongoDBNamespace { db: 'Mydb', collection: 'POC_DB' },
cmd:
{ find: 'Mydb.POC_DB',
limit: 0,
skip: 0,
query: {},
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: ReadPreference { mode: 'primary', tags: undefined } },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: ReadPreference { mode: 'primary', tags: undefined },
db:
Db {
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
promiseLibrary: [Function: Promise] },
topology:
Server {
_events:
{ serverOpening: [Function],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
commandStarted: [Function],
commandSucceeded: [Function],
commandFailed: [Function],
joined: [Function],
left: [Function],
ping: [Function],
ha: [Function],
authenticated: [Function],
error: [Array],
timeout: [Array],
close: [Array],
parseError: [Array],
open: [Array],
fullsetup: [Array],
all: [Array],
reconnect: [Array] },
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v10.13.0, LE' },
s:
{ coreTopology: [Server],
sCapabilities: [ServerCapabilities],
clonedOptions: [Object],
reconnect: true,
emitError: true,
poolSize: 5,
storeOptions: [Object],
store: [Store],
host: 'localhost',
port: 27017,
options: [Object],
sessionPool: [ServerSessionPool],
sessions: Set {},
promiseLibrary: [Function: Promise] } },
cursorState:
{ cursorId: null,
cmd:
{ find: 'Mydb.POC_DB',
limit: 0,
skip: 0,
query: {},
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [ReadPreference] },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined,
reconnect: true },
logger: Logger { className: 'Cursor' },
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
promiseLibrary: [Function: Promise],
currentDoc: null,
explicitlyIgnoreSession: false } }
.find() returns the result as an array if it exists so you have to get like result[0].name to get the data.
You should also check the length of the array in order not to get the out of bound exception.
According to MongoDB, if you are using find() method, they will return an array of document. So you need to access to that array to get your result (array[index].name). If you want to find just one document, you can use findOne() method.
I have the following selection query:
student.findCourses = (fcallback) => {
global.db.collection('students').find(({}, { "courses.courseName": true, _id: false }), (err, result) => {
if (err) {
var jError = { "status": "error", "message": "ERROR -> student.js -> 001" }
console.log(jError)
return fcallback(true, jError)
}
var jOk = { "status": "ok", "message": "student.js -> found -> 000" }
console.log(jOk)
console.log(result);
return fcallback(false, jOk)
})
}
And this is what I get in the console. I get status ok however it seems odd to me the response.
{ status: 'ok', message: 'student.js -> found -> 000' }
Cursor {
pool: null,
server: null,
disconnectHandler:
Store {
s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: BSON {},
ns: 'kea.students',
cmd:
{ find: 'kea.students',
limit: 0,
skip: 0,
query: { 'courses.courseName': true, _id: false },
readPreference: ReadPreference { preference: 'primary', tags: undefined, options: [Object] },
slaveOk: true },
options:
{ readPreference: ReadPreference { preference: 'primary', tags: undefined, options: [Object] },
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
db:
Db {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
promiseLibrary: [Function: Promise],
disconnectHandler: Store { s: [Object], length: [Getter] } },
topology:
Server {
domain: null,
_events:
{ reconnect: [Function: reconnectHandler],
reconnectFailed: [Function: reconnectFailedHandler],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
attemptReconnect: [Function],
monitoring: [Function],
timeout: [Function],
error: [Object],
close: [Function],
destroy: [Function: destroyHandler] },
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s:
{ options: [Object],
logger: [Object],
Cursor: [Object],
bson: BSON {},
pool: [Object],
disconnectHandler: [Object],
monitoring: true,
inTopology: false,
monitoringInterval: 5000,
topologyId: -1,
serverDescription: [Object],
topologyDescription: [Object] },
ismaster:
{ ismaster: true,
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 1000,
localTime: 2017-11-06T19:51:35.856Z,
maxWireVersion: 5,
minWireVersion: 0,
readOnly: false,
ok: 1 },
lastIsMasterMS: 10,
monitoringProcessId:
Timeout {
_called: false,
_idleTimeout: 5000,
_idlePrev: [Object],
_idleNext: [Object],
_idleStart: 657,
_onTimeout: [Function],
_timerArgs: undefined,
_repeat: null },
initalConnect: false,
wireProtocolHandler: WireProtocol { legacyWireProtocol: WireProtocol {} },
_type: 'server',
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v6.11.4, LE, mongodb-core: 2.1.17' },
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
cursorState:
{ cursorId: null,
cmd:
{ find: 'kea.students',
limit: 0,
skip: 0,
query: [Object],
readPreference: [Object],
slaveOk: true },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined },
logger: Logger { className: 'Cursor' },
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: BSON {},
ns: 'kea.students',
cmd:
{ find: 'kea.students',
limit: 0,
skip: 0,
query: [Object],
readPreference: [Object],
slaveOk: true },
options:
{ readPreference: [Object],
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
db: [Object],
promiseLibrary: [Function: Promise],
disconnectHandler: [Object] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s: [Object],
ismaster: [Object],
lastIsMasterMS: 10,
monitoringProcessId: [Object],
initalConnect: false,
wireProtocolHandler: [Object],
_type: 'server',
clientInfo: [Object],
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
topologyOptions:
{ host: 'localhost',
port: 27017,
disconnectHandler: [Object],
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
socketOptions: {},
socketTimeout: 360000,
connectionTimeout: 30000,
clientInfo: [Object],
readPreference: [Object],
promiseLibrary: [Function: Promise],
bson: BSON {} },
promiseLibrary: [Function: Promise],
currentDoc: null },
sortValue: undefined }
at Module.load (module.js:487:32)
I want to get only the data from the query, which is the following:
{ "courses": [
{
"courseName": "Web-development"
},
{
"courseName": "Databases"
},
{
"courseName": "Interface-Design"
}
]
}
I am not sure if there is something wrong with my query or with the way I am asking for the result?
When I do an insertion indeed I say console.log(JSON.stringify(result.ops)) which gives me only the inserted data, but if I use that for the selection it gives me undefined.
That´s why I am not sure if the query is actually working or you just ask in a different way to get the selected data?
From documentation. find return a cursor
https://docs.mongodb.com/manual/reference/method/db.collection.find/
This is what you see in console
In order to get results you can use toArray
https://docs.mongodb.com/manual/reference/method/cursor.toArray/
global.db.collection('students')
.find(({}, { "courses.courseName": 1, _id: 0}).toArray()
.then((data) => {//you will have your result here})
.catch(err => {//error if something wrong});
or in old way
global.db.collection('students')
.find(({}, { "courses.courseName": 1, _id: 0})
.toArray((err,data) => {//do stuff here});
Hope this helps.
i am just starting with NodeJs, I followed a few tutorials but after I try to do it by myself I am struggling with some things.
I'm trying to edit a post saved into my Mlab (Mongo) database. But I can't reach my values even if I have a good response:
My server.js code
app.get('/post/:id/edit', function(req,res){
console.log(req.params.id)
db.collection('posts').find({_id:ObjectId(req.params.id)},{},{}, function(err, result){
console.log(result)
if (err) return console.log(err)
res.render('edit.ejs', {post: result})
})
})
As a result I'm getting the below: (no text or title as expected)
Readable {
pool: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: 'analistafuncionalblog.posts',
cmd:
{ find: 'analistafuncionalblog.posts',
limit: 0,
skip: 0,
query: { _id: 5921bf9aff2e7524b4552480 },
readPreference: { preference: 'primary', tags: undefined, options: [Object] },
slaveOk: true,
fields: {} },
options:
{ readPreference: { preference: 'primary', tags: undefined, options: [Object] },
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
db:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
promiseLibrary: [Function: Promise],
disconnectHandler: { s: [Object], length: [Getter] } },
topology:
EventEmitter {
domain: null,
_events:
{ reconnect: [Function],
reconnectFailed: [Function],
timeout: [Function],
error: [Object],
close: [Function],
destroy: [Function],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
attemptReconnect: [Function],
monitoring: [Function] },
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s:
{ options: [Object],
logger: [Object],
Cursor: [Object],
bson: {},
pool: [Object],
disconnectHandler: [Object],
monitoring: true,
inTopology: false,
monitoringInterval: 5000,
topologyId: -1 },
ismaster:
{ hosts: [Object],
setName: 'rs-ds149221',
setVersion: 1,
ismaster: true,
secondary: false,
primary: 'ds149221-a.mlab.com:49221',
me: 'ds149221-a.mlab.com:49221',
electionId: 7fffffff0000000000000001,
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 1000,
localTime: Sun May 21 2017 16:50:58 GMT-0300 (Argentina Standard Time),
maxWireVersion: 4,
minWireVersion: 0,
ok: 1 },
lastIsMasterMS: 168,
monitoringProcessId:
{ _called: false,
_idleTimeout: 5000,
_idlePrev: [Object],
_idleNext: [Object],
_idleStart: 17129,
_onTimeout: [Function],
_repeat: null },
initalConnect: false,
wireProtocolHandler: { legacyWireProtocol: {} },
_type: 'server',
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v4.4.7, LE, mongodb-core: 2.1.10' },
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
cursorState:
{ cursorId: null,
cmd:
{ find: 'analistafuncionalblog.posts',
limit: 0,
skip: 0,
query: [Object],
readPreference: [Object],
slaveOk: true,
fields: {} },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined },
logger: { className: 'Cursor' },
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: {},
ns: 'analistafuncionalblog.posts',
cmd:
{ find: 'analistafuncionalblog.posts',
limit: 0,
skip: 0,
query: [Object],
readPreference: [Object],
slaveOk: true,
fields: {} },
options:
{ readPreference: [Object],
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
db: [Object],
promiseLibrary: [Function: Promise],
disconnectHandler: [Object] },
topology:
EventEmitter {
domain: null,
_events: [Object],
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s: [Object],
ismaster: [Object],
lastIsMasterMS: 168,
monitoringProcessId: [Object],
initalConnect: false,
wireProtocolHandler: [Object],
_type: 'server',
clientInfo: [Object],
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
topologyOptions:
{ host: 'ds149221.mlab.com',
port: 49221,
disconnectHandler: [Object],
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
socketOptions: {},
socketTimeout: 30000,
connectionTimeout: 30000,
clientInfo: [Object],
readPreference: [Object],
promiseLibrary: [Function: Promise],
bson: {} },
promiseLibrary: [Function: Promise],
currentDoc: null },
sortValue: undefined }
In my Mlab I keep my collection like:
{
"_id": {
"$oid": "5921bf9aff2e7524b4552480"
},
"title": "Prueba 1",
"text": "Ezequiel prueba texto"
}
how can I get the title and the text?
Thanks
collection.find() returns a cursor, which you need to read from in order to get the actual documents from the database.
For that, you can use cursor.toArray():
db.collection('posts').find({
_id : ObjectId(req.params.id)
}).toArray(function(err, results) {
...
});
However, since you're searching on a unique property (_id), you could also use collection.findOne():
db.collection('posts').findOne({ _id : ObjectId(req.params.id) }, function(err, post) {
...
});
I suggest you to use Mongoose, it allows you to do a lot of useful things, and is very easy to use. In your case, you can define a schema for the db and then apply all the mongoDB query on it.
Your record.js looks like that:
var mongoose = require('mongoose');
var Record = mongoose.Schema({
title: {type: String, required: true},
text: {type: String, required: true}
});
module.exports = mongoose.model('Record', Record);
Then in a new file, you can import the model and make all the query that you need:
var mongoose = require('mongoose');
var Record = require('./record');
mongoose.connect('mongodb://localhost/YOURDB');
app.get('/post/:id/edit', function(req,res){
console.log(req.params.id)
Record.findById(req.params.id, function(err, record){
if(err) throw err;
else return res.render('edit.ejs', {post: result});
});
});
I'm new to node,express & mongodb,
i need to retrive data from a mongo collection but when i execute the db.collection('mycoll').fine() method it puts back much data but not my required data which is colelction's records.
Here is my server side logic:
var url = 'mongodb://localhost:27017/wdk';
var resultArray = {};
mongodb.connect(url, function (err, db) {
var cursor = db.collection('projects').find({username:"new"});
cursor.forEach(function (docs,err) {
resultArray.push(docs);
}, function () {
db.close();
res.render('index',{
items:resultArray,
name: profile_name,
email: profile_email
});
});
console.log(cursor);
And here is what it returns in console:
Readable {
pool: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: 'wdk.projects',
cmd:
{ find: 'wdk.projects',
limit: 0,
skip: 0,
query: { pusername: 'extra' },
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: undefined } },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: undefined },
db:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
promiseLibrary: [Function: Promise],
disconnectHandler: { s: [Object], length: [Getter] } },
topology:
EventEmitter {
domain: null,
_events:
{ reconnect: [Function],
timeout: [Object],
error: [Object],
close: [Function],
destroy: [Object],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHearbeatFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function] },
_eventsCount: 14,
_maxListeners: undefined,
s:
{ options: [Object],
callbacks: [Object],
logger: [Object],
state: 'connected',
reconnect: true,
reconnectTries: 30,
reconnectInterval: 1000,
emitError: true,
currentReconnectRetry: 30,
ismaster: [Object],
readPreferenceStrategies: undefined,
authProviders: [Object],
id: 3,
topologyId: -1,
tag: undefined,
disconnectHandler: [Object],
monitoring: false,
haInterval: 10000,
wireProtocolHandler: [Object],
Cursor: [Object],
bsonInstance: {},
inquireServerStateTimeout: null,
bson: {},
pool: [Object],
isMasterLatencyMS: 1,
inTopology: false,
serverDetails: [Object],
serverDescription: null,
topologyDescription: null },
hashedName: '1309e35791f04f1f4fc35d5e683e81d350dd04f4',
name: [Getter],
bson: [Getter],
wireProtocolHandler: [Getter],
id: [Getter] },
cursorState:
{ cursorId: null,
cmd:
{ find: 'wdk.projects',
limit: 0,
skip: 0,
query: [Object],
slaveOk: true,
readPreference: [Object] },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined },
callbacks: null,
logger: { className: 'Cursor' },
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: {},
ns: 'wdk.projects',
cmd:
{ find: 'wdk.projects',
limit: 0,
skip: 0,
query: [Object],
slaveOk: true,
readPreference: [Object] },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [Object],
db: [Object],
promiseLibrary: [Function: Promise],
disconnectHandler: [Object] },
topology:
EventEmitter {
domain: null,
_events: [Object],
_eventsCount: 14,
_maxListeners: undefined,
s: [Object],
hashedName: '1309e35791f04f1f4fc35d5e683e81d350dd04f4',
name: [Getter],
bson: [Getter],
wireProtocolHandler: [Getter],
id: [Getter] },
topologyOptions:
{ socketOptions: {},
auto_reconnect: true,
host: 'localhost',
port: 27017,
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
disconnectHandler: [Object],
{ find: 'wdk.projects',
limit: 0,
skip: 0,
query: { pusername: 'extra' },
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: undefined } },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: undefined },
db:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
promiseLibrary: [Function: Promise],
disconnectHandler: { s: [Object], length: [Getter] } },
topology:
EventEmitter {
domain: null,
_events:
{ reconnect: [Function],
timeout: [Object],
error: [Object],
close: [Function],
destroy: [Object],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHearbeatFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function] },
_eventsCount: 14,
_maxListeners: undefined,
s:
{ options: [Object],
callbacks: [Object],
logger: [Object],
state: 'connected',
reconnect: true,
reconnectTries: 30,
reconnectInterval: 1000,
emitError: true,
currentReconnectRetry: 30,
ismaster: [Object],
readPreferenceStrategies: undefined,
authProviders: [Object],
id: 3,
topologyId: -1,
tag: undefined,
disconnectHandler: [Object],
monitoring: false,
haInterval: 10000,
wireProtocolHandler: [Object],
Cursor: [Object],
bsonInstance: {},
inquireServerStateTimeout: null,
bson: {},
pool: [Object],
isMasterLatencyMS: 1,
inTopology: false,
serverDetails: [Object],
serverDescription: null,
topologyDescription: null },
hashedName: '1309e35791f04f1f4fc35d5e683e81d350dd04f4',
name: [Getter],
bson: [Getter],
wireProtocolHandler: [Getter],
id: [Getter] },
cursorState:
{ cursorId: null,
cmd:
{ find: 'wdk.projects',
limit: 0,
skip: 0,
query: [Object],
slaveOk: true,
readPreference: [Object] },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined },
callbacks: null,
logger: { className: 'Cursor' },
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: {},
ns: 'wdk.projects',
cmd:
{ find: 'wdk.projects',
limit: 0,
skip: 0,
query: [Object],
slaveOk: true,
readPreference: [Object] },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [Object],
db: [Object],
promiseLibrary: [Function: Promise],
disconnectHandler: [Object] },
topology:
EventEmitter {
domain: null,
_events: [Object],
_eventsCount: 14,
_maxListeners: undefined,
s: [Object],
hashedName: '1309e35791f04f1f4fc35d5e683e81d350dd04f4',
name: [Getter],
bson: [Getter],
wireProtocolHandler: [Getter],
messageHandler: [Function],
wireProtocolHandler: [Object] },
promiseLibrary: [Function: Promise],
currentDoc: null },
ignoreUndefined: false,
maxBsonSize: 16777216,
checkKeys: false,
batchSize: -1,
tailable: false,
slaveOk: false,
oplogReplay: false,
noCursorTimeout: false,
awaitData: false,
exhaust: false,
partial: false,
documentsReturnedIn: 'firstBatch' } }
And here is what's i get when i query on mongo console:
enter image description here
Your console.log() is logging the cursor object, not the list of results. For that, you need to log resultArray in the final callback (which is also the right location to check for errors):
cursor.forEach(function(doc) {
resultArray.push(doc);
}, function (err) {
if (err) ... // handle error!
console.log('results:', resultArray);
db.close();
res.render('index',{
items : resultArray,
name : profile_name,
email : profile_email
});
});
I use this code to connect to my mongo db localhost and find the "names" but i have a problem in consol.log:
url = require("url"),
emitter = require("events").EventEmitter,
assert = require("assert"),
mongo = require("mongodb"),
Cursor = mongo.Cursor;
var uristring = "mongodb://localhost:27017/test";
var mongoUrl = url.parse (uristring);
mongo.MongoClient.connect (uristring, function (err, db) {
var test = db.collection ("test")
console.log ("Success connecting to " + mongoUrl.protocol + "//" + mongoUrl.hostname + ".");
console.log (test.find({},{name:1,_id:0}));
db.close();
});
when i use db.test.find({},{name:1,_id:0}) in my terminal in mongo its returning { "name" : "pooya" }
but in nodjs code it return:
Success connecting to mongodb://localhost.
{ db:
{ domain: null,
_events: {},
_maxListeners: 10,
databaseName: 'test',
serverConfig:
{ domain: null,
_events: {},
_maxListeners: 10,
_callBackStore: [Object],
_commandsStore: [Object],
auth: [Object],
_dbStore: [Object],
host: 'localhost',
port: 27017,
options: [Object],
internalMaster: true,
connected: true,
poolSize: 5,
disableDriverBSONSizeCheck: false,
_used: true,
replicasetInstance: null,
emitOpen: false,
ssl: false,
sslValidate: false,
sslCA: null,
sslCert: undefined,
sslKey: undefined,
sslPass: undefined,
serverCapabilities: [Object],
name: 'localhost:27017',
socketOptions: [Object],
logger: [Object],
eventHandlers: [Object],
_serverState: 'connected',
_state: [Object],
recordQueryStats: false,
socketTimeoutMS: [Getter/Setter],
_readPreference: [Object],
db: [Circular],
dbInstances: [Object],
connectionPool: [Object],
isMasterDoc: [Object] },
options:
{ read_preference_tags: null,
read_preference: 'primary',
url: 'mongodb://localhost:27017/test',
native_parser: true,
readPreference: [Object],
safe: false,
w: 1 },
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
native_parser: true,
bsonLib:
{ BSON: [Object],
Long: [Object],
ObjectID: [Object],
DBRef: [Function: DBRef],
Code: [Function: Code],
Timestamp: [Object],
Binary: [Object],
Double: [Function: Double],
MaxKey: [Function: MaxKey],
MinKey: [Function: MinKey],
Symbol: [Function: Symbol] },
bson: { promoteLongs: true },
bson_deserializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Object],
DBRef: [Function: DBRef],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey],
promoteLongs: true },
bson_serializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Object],
DBRef: [Function: DBRef],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey],
promoteLongs: true },
_state: 'connected',
pkFactory:
{ [Function: ObjectID]
index: 2954887,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid] },
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
openCalled: true,
commands: [],
logger: { error: [Function], log: [Function], debug: [Function] },
tag: 1416152062206,
eventHandlers:
{ error: [],
parseError: [],
poolReady: [],
message: [],
close: [] },
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined } },
collection:
{ db:
{ domain: null,
_events: {},
_maxListeners: 10,
databaseName: 'test',
serverConfig: [Object],
options: [Object],
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
native_parser: true,
bsonLib: [Object],
bson: [Object],
bson_deserializer: [Object],
bson_serializer: [Object],
_state: 'connected',
pkFactory: [Object],
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
openCalled: true,
commands: [],
logger: [Object],
tag: 1416152062206,
eventHandlers: [Object],
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: [Object] },
collectionName: 'test',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
pkFactory:
{ [Function: ObjectID]
index: 2954887,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid] },
serverCapabilities: undefined },
selector: {},
fields: { name: 1, _id: 0 },
skipValue: 0,
limitValue: 0,
sortValue: undefined,
hint: null,
explainValue: undefined,
snapshot: undefined,
timeout: true,
tailable: undefined,
awaitdata: undefined,
oplogReplay: undefined,
numberOfRetries: 5,
currentNumberOfRetries: 5,
batchSizeValue: 0,
raw: false,
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
returnKey: undefined,
maxScan: undefined,
min: undefined,
max: undefined,
showDiskLoc: undefined,
comment: undefined,
tailableRetryInterval: 100,
exhaust: false,
partial: false,
slaveOk: false,
maxTimeMSValue: undefined,
connection: undefined,
totalNumberOfRecords: 0,
items: [],
cursorId: { _bsontype: 'Long', low_: 0, high_: 0 },
dbName: undefined,
state: 0,
queryRun: false,
getMoreTimer: false,
collectionName: 'test.test' }
why its happening?how to solve it?
Welcome to StackOverflow.
You are using the API wrongly. The MongoDB driver returns the query results asynchronously, via callback, not synchronously like in most languages you probably met so far, if you are new to node.js.
So, basically you are doing this
var results = test.find({},{name:1,_id:0})
console.log (results);
But what you really want to do is:
test.find({name:1,_id:0}, new function(error, results)
{
if(error! = null) console.log(error);
else //do whatever you want with the results
});
Keep in mind that the code after test.find() will keep running independently of the query and its results. The results processing will be called when the query is finished.
Btw. I also think parameters passed to your find() method are somehow wrong. The query should be the first parameter, and in your example it's second, if I'm not mistaken. The method looks like this: find(query[, options], callback).
You can find the documentation of the MongoDB driver here, including the find method.
You should more or less do the same with the find() method as you did with the connect() method in which callback you are writing the query.
If you are not comfortable with the notion of asynchronous, event driven or non-blocking programming please consider reading these links:
http://book.mixu.net/node/ch7.html
http://justinklemm.com/node-js-async-tutorial/
EDIT:
Sorry, I must edit myself. The callback has two parameters, the FIRST one is the error, the SECOND are the results. Haven't used this for a while.