the nodejs and mongo db find - node.js

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.

Related

How to get values from a mongodb cursor from a collection with elements

I'm trying to build a live chart out of a simple mongo colection, using Raspberry Pi 2 with dietPi (DietPi v6.22.3), mongodb and nodejs.
What I'm trying to do is to get data from the db using something like:
var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/DB_A';
var str = "";
app.route('/PAGE_A').get(function (req, res) {
MongoClient.connect(url, function (err, db) {
if (err) {
console.log(err);
} else {
console.log("Connected to db");
var cursor = db.collection('COL_A').find();
console.log(cursor);
//noinspection JSDeprecatedSymbols
cursor.each(function (err, item) {
if (item != null) {
str = str + " DateTime " + item.dt + " - Users: " + item.users + " </br>";
}
});
res.send(str);
db.close();
}
});
});
var server = app.listen(8080, function () {});
Running node app.js and accessing the designated IP:8080/page_A I get the "Connected to db" message but no expected data from the cursor is being printed, except for its parameters I used for this question.
The collection is not empty. I can use DB_A and get elements from db.COL_A.find()...
This is what I get printed in the console when I "npm start" and access IP/PAGE_A:
Connected to db
Cursor {
db:
Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
databaseName: 'DB_A',
serverConfig:
Server {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
_callBackStore: [CallbackStore],
host: 'localhost',
port: 27017,
options: [Object],
internalMaster: true,
connected: true,
poolSize: 5,
disableDriverBSONSizeCheck: false,
slaveOk: undefined,
_used: true,
replicasetInstance: null,
ssl: false,
sslValidate: false,
sslCA: null,
sslCert: undefined,
sslKey: undefined,
sslPass: undefined,
_readPreference: null,
socketOptions: [Object],
logger: [Object],
eventHandlers: [Object],
_serverState: 'connected',
_state: [Object],
recordQueryStats: false,
db: [Circular],
dbInstances: [Array],
connectionPool: [EventEmitter],
isMasterDoc: [Object] },
options:
{ read_preference_tags: null,
read_preference: 'primary',
native_parser: false,
readPreference: [ReadPreference],
safe: false,
w: 1 },
_applicationClosed: false,
native_parser: false,
bsonLib:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Function],
DBRef: [Function: DBRef],
Binary: [Function],
ObjectID: [Function],
Long: [Function],
Timestamp: [Function],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey] },
bson: BSON {},
bson_deserializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Function],
DBRef: [Function: DBRef],
Binary: [Function],
ObjectID: [Function],
Long: [Function],
Timestamp: [Function],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey] },
bson_serializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Function],
DBRef: [Function: DBRef],
Binary: [Function],
ObjectID: [Function],
Long: [Function],
Timestamp: [Function],
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: false,
notReplied: {},
isInitializing: true,
auths: [],
openCalled: true,
commands: [],
logger:
{ error: [Function: error],
log: [Function: log],
debug: [Function: debug] },
slaveOk: false,
tag: 1554299599878,
eventHandlers:
{ error: [],
parseError: [],
poolReady: [],
message: [],
close: [] },
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference:
ReadPreference { _type: 'ReadPreference', mode: 'primary', tags: undefined } },
collection:
Collection {
db:
Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
databaseName: 'DB_A',
serverConfig: [Server],
options: [Object],
_applicationClosed: false,
native_parser: false,
bsonLib: [Object],
bson: BSON {},
bson_deserializer: [Object],
bson_serializer: [Object],
_state: 'connected',
pkFactory: [Function],
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
auths: [],
openCalled: true,
commands: [],
logger: [Object],
slaveOk: false,
tag: 1554299599878,
eventHandlers: [Object],
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: [ReadPreference] },
collectionName: 'COL_A',
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: Long { _bsontype: 'Long', low_: 0, high_: 0 },
dbName: undefined,
state: 0,
queryRun: false,
getMoreTimer: false,
collectionName: 'DB_A.COL_A' }
Here are some details on my setup:
mongod --version
db version v2.4.14
node --version
v10.15.3
NodeJS mongo driver -> 1.2.13
cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 9 (stretch)"
NAME="Raspbian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
ID=raspbian
ID_LIKE=debian
HOME_URL="http://www.raspbian.org/"
SUPPORT_URL="http://www.raspbian.org/RaspbianForums"
BUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"
cat /etc/debian_version
9.8
uname -a
Linux DietPi 4.14.98+ #1200 Tue Feb 12 20:11:02 GMT 2019 armv6l GNU/Linux
cat /proc/cpuinfo
processor : 0
model name : ARMv6-compatible processor rev 7 (v6l)
BogoMIPS : 697.95
Features : half thumb fastmult vfp edsp java tls
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xb76
CPU revision : 7
Hardware : BCM2835
Revision : 000e
Serial : 00000000ce0ee037
Thank you.
if you want desire result you can get it using async await
MongoClient.connect(url, async (err, db) => {
if (err) {
console.log(err);
} else {
console.log("Connected to db");
var cursor = await db.collection("comments").find().toArray();
console.log({ cursor });
db.close();
}
});
But if you want to use cursor type with each method of cursor not sure why not working
also change mongodb version "^3.2.2" to "^2.2.33" no luck

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.

Trouble getting a response from cursor.toArray() in Mongo/Node

node 0.10.24 + mongo node driver 1.3.23 on 32 bit linux
My callback here is never getting executed.
console.log(record_collection);
record_collection.find({}, function (error, cursor) {
console.log("record_collection.find() returned");
if (error) {
console.log(error);
callback(error);
}
else {
console.log("calling toArray with cursor");
cursor.toArray(function(error, docs){
console.log("cursor.toArray() returned");
if (error) {
console.log(error);
callback(error);
}
else {
callback(null, docs);
}
});
}
});
The output from this section goes like this:
{ db:
{ domain: null,
_events: {},
_maxListeners: 10,
databaseName: 'dbname',
serverConfig:
{ domain: null,
_events: {},
_maxListeners: 10,
_callBackStore: [Object],
_commandsStore: [Object],
auth: [Object],
_dbStore: [Object],
host: 'localhost',
port: 27017,
options: [Object],
internalMaster: false,
connected: false,
poolSize: 5,
disableDriverBSONSizeCheck: false,
_used: true,
replicasetInstance: null,
emitOpen: true,
ssl: false,
sslValidate: false,
sslCA: null,
sslCert: undefined,
sslKey: undefined,
sslPass: undefined,
serverCapabilities: null,
name: 'localhost:27017',
_readPreference: null,
socketOptions: [Object],
logger: [Object],
eventHandlers: [Object],
_serverState: 'connecting',
_state: [Object],
recordQueryStats: false,
socketTimeoutMS: [Getter/Setter],
db: [Circular],
dbInstances: [Object],
connectionPool: [Object] },
options: {},
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
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],
promoteLongs: true },
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: 'connecting',
pkFactory:
{ [Function: ObjectID]
index: 14382708,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] },
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
openCalled: true,
commands: [],
logger: { error: [Function], log: [Function], debug: [Function] },
tag: 1390462362041,
eventHandlers:
{ error: [],
parseError: [],
poolReady: [],
message: [],
close: [] },
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: undefined },
collectionName: 'gis_stops',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: 'primary',
pkFactory:
{ [Function: ObjectID]
index: 14382708,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] },
serverCapabilities: undefined }
record_collection.find() returned
calling toArray with cursor
It looks like the first console.log() of the collection doesn't finish. But the other traces appear. Why isn't the callback being executed? Why don't I see "cursor.toArray() returned"?
This stopped working when I moved to a new server. The old server was running node 0.10.13 and mongodb 1.2.13.
From the record_collection trace:
db.serverConfig.connected = false;
The database was not connected.

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)

Can't return a string properly with mongoskin

So I have this script:
var db = require('mongoskin').db('localhost:27017/titles', {safe:true});
var titles = db.collection('titles');
title = titles.findOne(function(err, result){
if (err) throw err;
return result.title;
});
console.log(title)
And this BSON object in the collection:
{"title": "Hello World", "postNumber": 0, "_id": ObjectId("509eeffbf8f11e8813000001")}
My goal is got get the string "Hello World" to output to the console, but instead I get this:
{ emitter: { _events: { open: [Object] }, _maxListeners: 50 },
state: 1,
options: undefined,
skinDb:
{ emitter: { _events: [Object], _maxListeners: 100 },
state: 1,
_dbconn:
{ databaseName: 'titles',
serverConfig: [Object],
options: [Object],
_applicationClosed: false,
native_parser: true,
bsonLib: [Object],
bson: {},
bson_deserializer: [Object],
bson_serializer: [Object],
_state: 'connecting',
pkFactory: [Object],
forceServerObjectId: false,
safe: true,
notReplied: {},
isInitializing: true,
auths: [],
openCalled: true,
commands: [],
_callBackStore: [Object],
logger: [Object],
slaveOk: false,
tag: 1352682584657,
eventHandlers: [Object],
serializeFunctions: false,
raw: false,
recordQueryStats: false,
reaperEnabled: false,
_lastReaperTimestamp: 1352682584657,
retryMiliSeconds: 1000,
numberOfRetries: 60,
reaperInterval: 10000,
reaperTimeout: 30000,
readPreference: undefined },
db: null,
username: '',
password: undefined,
admin: { emitter: {}, state: 0, skinDb: [Circular], admin: null },
_collections: { titles: [Circular] },
bson_serializer:
{ 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] },
ObjectID:
{ [Function: ObjectID]
index: 0,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] } },
ObjectID:
{ [Function: ObjectID]
index: 0,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] },
collectionName: 'titles',
collection: null,
internalHint: null,
hint: [Getter/Setter] }
It works just fine when I put the console.log() inside the function, I just can't return the string for some reason.
Solved:
read = function(callback){
titles.findOne(function(err, result){
if (err) throw err;
callback(result.title);
});
};
read(function(title){
console.log(title);
});
you need to understand javascript callback.
1 - findOne will return a db object not the result of your string. I never read the mongoskin doco but I think it will be a db collection or some sort which is what you see in the console.log print out.
2 - in the callback your do return result.title; will never return the title back as you would expect. so that is why I suggest to do some reading on how callback work.
The correct way to print the title will be putting the console.log inside the callback function as you mention.

Resources