Selection in mongoDb return weird stuff - node.js

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.

Related

Unable to retrieve data from mongodb to Node JS [duplicate]

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.

NodeJS - find by Id not working

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

Mongoose does not query my collection using .find() method

I connected to the collection and then began my query on the collectionto find all documents with this query. However when I log the result I get a Readable object, which I assume is a stream. I used some stream methods on it but it only returns one document. I'm not sure why it doesn't return json.
const path = require('path'),
User = require(path.join(__dirname, '../models/user.js')),
Card = require(path.join(__dirname, '../models/card.js')),
mongoose = require('mongoose');
module.exports = {
get: (req, res) => {
const foo = mongoose.connection.db.collection('foo');
Card.find({ _id: {$in: req.user.cards } },
{ name: 1,
bank: 1 }).exec(function(err, cards) {
if (err) throw err;
// Problem: does not return documents or error
foo.find({ bank: 'chase'}, { name: 1, bank: 1, value: 1 }, function(err, bonus) {
if (err) throw err;
console.log(bonus);
});
});
}
}
Here is the output. I don't think my query is executing but I don't know where to go from here.
Readable {
pool: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: 'kard_development.kard_bonus',
cmd:
{ find: 'kard_development.kard_bonus',
limit: 0,
skip: 0,
query: { bank: 'Chase' },
slaveOk: false },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: false,
db:
EventEmitter {
domain: null,
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
_listening: true },
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: 0,
topologyId: -1,
tag: undefined,
disconnectHandler: [Object],
monitoring: false,
haInterval: 10000,
wireProtocolHandler: [Object],
Cursor: [Object],
bsonInstance: {},
inquireServerStateTimeout: null,
bson: {},
pool: [Object],
isMasterLatencyMS: 8,
inTopology: false,
serverDetails: [Object],
serverDescription: null,
topologyDescription: null },
hashedName: '1309e35791f04f1f4fc35d5e683e81d350dd04f4',
name: [Getter],
bson: [Getter],
wireProtocolHandler: [Getter],
id: [Getter] },
cursorState:
{ cursorId: null,
cmd:
{ find: 'kard_development.kard_bonus',
limit: 0,
skip: 0,
query: [Object],
slaveOk: false },
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,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain:
Domain {
domain: null,
_events: { error: [Function] },
_eventsCount: 1,
_maxListeners: undefined,
members: [] },
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: {},
ns: 'kard_development.kard_bonus',
cmd:
{ find: 'kard_development.kard_bonus',
limit: 0,
skip: 0,
query: [Object],
slaveOk: false },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: false,
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],
bson: {},
messageHandler: [Function],
wireProtocolHandler: [Object] },
promiseLibrary: [Function: Promise],
currentDoc: null },
sortValue: undefined }
If you're using Mongoose, it's known as an ODM for MongoDB, which is great if you're using of models/schemas, but for simple queries over a collection its a little weird. If you look at the Mongoose API http://mongoosejs.com/docs/api.html, the find methods are only available to models and queries, which is why your first find works, you are using the Card model.
However if you want to do a query on your collection, like you have in this line:
const foo = mongoose.connection.db.collection('foo');
It won't quite work as mongoose connection objects don't have a .find() method. One thing you can do is use the native MongoDB driver for Node, sort of what #dvlsg was alluding to in the comments, and you'll probably get what you are looking for.

get much data but nothing my required data from mongodb find() method

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

MongoDB (Node.js) find not returning expected result

I am trying to make a find from node to a mongodb server. Here is the code:
var mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db;
var mongoServer = new Server(10.141.74.74, 28019,{auto_reconnect: true, safe:true});
var db = new Db("statusReport", mongoServer, {safe:true});
db.open(function(err,db){
if(!err){
db.collection("status",function(err,collection){
if(!err){
collection.find({}, function(a,b){
console.log(a);
console.log(b);
});
}else{
console.log("ERROR: could not open collection");
}
});
db.close();
}else{
console.log("ERROR: could not open database");
}
});
However, instead of returning data it is returning this:
{ db:
{ domain: null,
_events: { open: [] },
_maxListeners: 10,
databaseName: 'statusReport',
serverConfig:
{ domain: null,
_events: null,
_maxListeners: 10,
host: '10.141.74.74',
port: 28019,
options: [Object],
internalMaster: true,
connected: true,
poolSize: 5,
disableDriverBSONSizeCheck: false,
ssl: false,
slaveOk: undefined,
_used: true,
_readPreference: null,
socketOptions: [Object],
logger: [Object],
eventHandlers: [Object],
_serverState: 'connected',
_state: [Object],
recordQueryStats: false,
dbInstance: [Circular],
dbInstances: [Object],
connectionPool: [Object],
isMasterDoc: [Object] },
options: { safe: true },
_applicationClosed: false,
native_parser: undefined,
bsonLib:
{ 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] },
bson: {},
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] },
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] },
_state: 'connected',
pkFactory:
{ [Function: ObjectID]
index: 0,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] },
forceServerObjectId: false,
safe: true,
notReplied: {},
isInitializing: true,
auths: [],
openCalled: true,
commands: [],
_callBackStore: { domain: null, _events: {}, _maxListeners: 10, _notReplied: {} },
logger: { error: [Function], log: [Function], debug: [Function] },
slaveOk: false,
tag: 1363118044637,
eventHandlers:
{ error: [],
parseError: [],
poolReady: [],
message: [],
close: [] },
serializeFunctions: false,
raw: false,
recordQueryStats: false,
reaperEnabled: false,
_lastReaperTimestamp: 1363118044637,
retryMiliSeconds: 1000,
numberOfRetries: 60,
reaperInterval: 10000,
reaperTimeout: 30000,
readPreference: undefined },
collection:
{ db:
{ domain: null,
_events: [Object],
_maxListeners: 10,
databaseName: 'statusReport',
serverConfig: [Object],
options: [Object],
_applicationClosed: false,
native_parser: undefined,
bsonLib: [Object],
bson: {},
bson_deserializer: [Object],
bson_serializer: [Object],
_state: 'connected',
pkFactory: [Object],
forceServerObjectId: false,
safe: true,
notReplied: {},
isInitializing: true,
auths: [],
openCalled: true,
commands: [],
_callBackStore: [Object],
logger: [Object],
slaveOk: false,
tag: 1363118044637,
eventHandlers: [Object],
serializeFunctions: false,
raw: false,
recordQueryStats: false,
reaperEnabled: false,
_lastReaperTimestamp: 1363118044637,
retryMiliSeconds: 1000,
numberOfRetries: 60,
reaperInterval: 10000,
reaperTimeout: 30000,
readPreference: undefined },
collectionName: 'status',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: 'primary',
pkFactory:
{ [Function: ObjectID]
index: 0,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] } },
selector: {},
fields: undefined,
skipValue: 0,
limitValue: 0,
sortValue: undefined,
hint: null,
explainValue: undefined,
snapshot: undefined,
timeout: true,
tailable: undefined,
awaitdata: undefined,
numberOfRetries: 5,
currentNumberOfRetries: 5,
batchSizeValue: 0,
slaveOk: false,
raw: false,
read: 'primary',
returnKey: undefined,
maxScan: undefined,
min: undefined,
max: undefined,
showDiskLoc: undefined,
comment: undefined,
tailableRetryInterval: 100,
exhaust: false,
partial: false,
totalNumberOfRecords: 0,
items: [],
cursorId: { _bsontype: 'Long', low_: 0, high_: 0 },
dbName: undefined,
state: 0,
queryRun: false,
getMoreTimer: false,
collectionName: 'statusReport.status' }
I know there is stuff in there because I can see it using MongoHub. I can also query it there too. What is wrong here?
I also tried doing collection.insert(some data here) and the insert works. Just the find does not.
collection.find(callback) returns the cursor, not the documents. you want to do:
collection.find().toArray(callback)

Resources