snatera snatera - 4 months ago 47
Node.js Question

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 }

Answer

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.