I am using MongoDB version 3.4.7, Mongoose 4.11.13 driver for creating Model on MongoDB collection and creating AggregationCursor to process each document individually to populate some JS variables. But it seems the Mongoose model is not bringing any data into the cursor from MongoDB collection.
I tried aggregate operation with mongodb driver previously but it doesn't work
(check here) and opted for mongoose instead. But it seems there is some problem here as well or I am missing anything here? Updated my AggregationCursor for better understanding. Any quick help will be greatly appreciated.
Node version 3.10.10, ExpressJS 3.2.6
My Node.JS code is as follows:
app.get('/reviews',function(req,res)
{
res.render("chart");
var obj = {};
var mongoose = require('mongoose');
var assert = require('assert');
var schema = new mongoose.Schema({
seller_id: String,
product_id: String,
product_desc: String,
reviews: {
total_review_count: Number,
five_star_count: Number,
four_star_count: Number,
three_star_count: Number,
two_star_count: Number,
one_star_count: Number
}
});
//specify the name of MongoDB collection as third argument of model
var ProductReview = mongoose.model('ProductReview', schema, 'product_reviews'); //<-- here
//review count placeholders
var totalReviewCounts = [], FiveStarCounts = [], FourStarCounts = [], ThreeStarCounts = [],
TwoStarCounts = [], OneStarCounts = [];
mongoose.connect('mongodb://localhost:27017/sellerrank', function() {
var cursor = ProductReview.aggregate([
{
$match: {
seller_id: { $exists: true, $nin: [null] }
}
}
])
.allowDiskUse(true)
.group({ _id: { seller_id: '$seller_id'},
total_review_count: {
$sum: {
$cond : [
{ $eq : ["$reviews.total_review_count", null] },
0,
"$reviews.total_review_count"
]
}
},
five_star_count: {
$sum: {
$cond : [
{ $eq : ["$reviews.five_star_count", null] },
0,
"$reviews.five_star_count"
]
}
},
four_star_count: {
$sum: {
$cond : [
{ $eq : ["$reviews.four_star_count", null] },
0,
"$reviews.four_star_count"
]
}
},
three_star_count: {
$sum: {
$cond : [
{ $eq : ["$reviews.three_star_count", null] },
0,
"$reviews.three_star_count"
]
}
},
two_star_count: {
$sum: {
$cond : [
{ $eq : ["$reviews.two_star_count", null] },
0,
"$reviews.two_star_count"
]
}
},
one_star_count: {
$sum: {
$cond : [
{ $eq : ["$reviews.one_star_count", null] },
0,
"$reviews.one_star_count"
]
}
}
})
.cursor({ batchSize: 100})
.exec();
console.log(cursor); **//<-- printing the cursor here**
cursor.each(function(err,doc){
assert.equal(null,err);
console.log(doc);
if(doc!=null){
var seller_id = doc['_id'];
var totalReviews = doc['total_review_count'];
var fiveStarReviews = doc['five_star_count'];
var fourStarReviews = doc['four_star_count'];
var threeStarReviews = doc['three_star_count'];
var twoStarReviews = doc['two_star_count'];
var oneStarReviews = doc['one_star_count'];
totalReviewCounts.push({"value" : totalReviews});
FiveStarCounts.push({"value" : fiveStarReviews});
FourStarCounts.push({"value" : fourStarReviews});
ThreeStarCounts.push({"value" : threeStarReviews});
TwoStarCounts.push({"value" : twoStarReviews});
OneStarCounts.push({"value" : oneStarReviews});
}
});
});
var dataset = [
{
"seriesname" : "Total positive reviews",
"data" : totalReviewCounts
},
{
"seriesname" : "5 star reviews",
"data": FiveStarCounts
},
{
"seriesname" : "4 star reviews",
"data" : FourStarCounts
},
{
"seriesname" : "3 star reviews",
"data": ThreeStarCounts
},
{
"seriesname" : "2 star reviews",
"data" : TwoStarCounts
},
{
"seriesname" : "1 star reviews",
"data": OneStarCounts
}
];
console.log(dataset); //<-- **dataset is printed here**
var response = {
"dataset" : dataset
};
obj['dataset'] = dataset;
console.log(obj);
res.send(obj);
mongoose.disconnect();
});
When I am running the above Node.JS Express code, I am getting the output of console.log(dataset) as
[ { seriesname: 'Total positive reviews', data: [] },
{ seriesname: '5 star reviews', data: [] },
{ seriesname: '4 star reviews', data: [] },
{ seriesname: '3 star reviews', data: [] },
{ seriesname: '2 star reviews', data: [] },
{ seriesname: '1 star reviews', data: [] } ]
There is data in my local MongoDB collection 'product_reviews' but there is no data fetched into the cursor.
My Aggregation cursor as shown in console.log(cursor) is as follows:
AggregationCursor {
pool: null,
server: null,
disconnectHandler:
Store {
s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: BSON {},
ns: 'sellerrank.product_reviews',
cmd:
{ aggregate: 'product_reviews',
pipeline: [ [Object], [Object] ],
allowDiskUse: true,
cursor: { batchSize: 100 } },
options:
{ allowDiskUse: true,
cursor: { batchSize: 100 },
promiseLibrary: [Function: Promise],
cursorFactory: { [Function: AggregationCursor] super_: [Object], define: [Object], INIT: 0, OPEN: 1, CLOSED: 2 },
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-10-02T14:21:27.032Z,
maxWireVersion: 5,
minWireVersion: 0,
readOnly: false,
ok: 1 },
lastIsMasterMS: 12,
monitoringProcessId:
Timeout {
_called: false,
_idleTimeout: 5000,
_idlePrev: [Object],
_idleNext: [Object],
_idleStart: 5621,
_onTimeout: [Function],
_timerArgs: undefined,
_repeat: null },
initalConnect: false,
wireProtocolHandler: WireProtocol { legacyWireProtocol: WireProtocol {} },
_type: 'server',
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v6.11.3, LE, mongodb-core: 2.1.15' },
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
cursorState:
{ cursorId: null,
cmd:
{ aggregate: 'product_reviews',
pipeline: [Object],
allowDiskUse: true,
cursor: [Object] },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 100,
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:
{ maxTimeMS: null,
state: 0,
streamOptions: {},
bson: BSON {},
ns: 'sellerrank.product_reviews',
cmd:
{ aggregate: 'product_reviews',
pipeline: [Object],
allowDiskUse: true,
cursor: [Object] },
options:
{ allowDiskUse: true,
cursor: [Object],
promiseLibrary: [Function: Promise],
cursorFactory: [Object],
disconnectHandler: [Object] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s: [Object],
ismaster: [Object],
lastIsMasterMS: 12,
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: {},
auto_reconnect: true,
clientInfo: [Object],
forceServerObjectId: false,
w: 1,
promiseLibrary: [Function: Promise],
bson: BSON {} },
promiseLibrary: [Function: Promise] },
sortValue: undefined,
eachAsync: [Function] }
Related
I am running a Mongo query from the Order database which aims to fetch the orders of a particular user by using his email. This is done using an API, but I am getting the complete object with some unnecessary details.
Code
I have written the following API in nextJS name myorders:
import Order from "../../models/Order";
import connectDB from "../../middleware/mongoose";
import jsonwebtoken from "jsonwebtoken";
const handler = async(req, res) => {
const token = req.body.token;
const data = jsonwebtoken.verify(token,process.env.JWT_SECRET);
console.log(data)
let mere_orders = Order.find({email: data.email})
console.log("mereorders12 = ", mere_orders)
res.status(200).json({mere_orders});
}
export default connectDB(handler);
And console.log("mereorders12 = ", mere_orders) gives me this:
mereorders12 = Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
_executionStack: null,
mongooseCollection: Collection {
collection: Collection { s: [Object] },
Promise: [Function: Promise],
modelName: 'Order',
_closed: false,
opts: {
autoIndex: true,
autoCreate: true,
schemaUserProvidedOptions: [Object],
capped: false,
Promise: [Function: Promise],
'$wasForceClosed': undefined
},
name: 'orders',
collectionName: 'orders',
conn: NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: {},
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype],
_readyState: 1,
_closeCalled: undefined,
_hasOpened: true,
plugins: [],
id: 0,
_queue: [],
_listening: false,
_connectionString: 'mongodb://localhost:27017/chesswear',
_connectionOptions: [Object],
client: [MongoClient],
'$initialConnection': [Promise],
db: [Db],
host: 'localhost',
port: 27017,
name: 'chesswear'
},
queue: [],
buffer: false,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { Order },
schema: Schema {
obj: {
email: [Object],
orderId: [Object],
paymentInfo: [Object],
products: [Object],
address: [Object],
subtotal: [Object],
status: [Object]
},
paths: {
email: [SchemaString],
orderId: [SchemaString],
paymentInfo: [SchemaString],
products: [Mixed],
address: [SchemaString],
subtotal: [SchemaNumber],
status: [SchemaString],
_id: [ObjectId],
updatedAt: [SchemaDate],
createdAt: [SchemaDate],
__v: [SchemaNumber]
},
aliases: {},
subpaths: {},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: { initializeTimestamps: [Function (anonymous)] },
methodOptions: {},
statics: {},
tree: {
email: [Object],
orderId: [Object],
paymentInfo: [Object],
products: [Object],
address: [Object],
subtotal: [Object],
status: [Object],
_id: [Object],
updatedAt: [Function: Date],
createdAt: [Object],
__v: [Function: Number],
id: [VirtualType]
},
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object] ],
'$id': 1,
mapPaths: [],
s: { hooks: [Kareem] },
_userProvidedOptions: { timestamps: true },
options: {
timestamps: true,
typeKey: 'type',
id: true,
_id: true,
validateBeforeSave: true,
read: null,
shardKey: null,
discriminatorKey: '__t',
autoIndex: null,
minimize: true,
optimisticConcurrency: false,
versionKey: '__v',
capped: false,
bufferCommands: true,
strictQuery: true,
strict: true,
pluralization: true
},
'$timestamps': { createdAt: 'createdAt', updatedAt: 'updatedAt' },
'$globalPluginsApplied': true,
_requiredpaths: [ 'status', 'subtotal', 'address', 'products', 'orderId', 'email' ]
},
op: 'find',
options: {},
_conditions: { email: 'mohit6#test.com' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection: NodeCollection {
collection: Collection {
collection: [Collection],
Promise: [Function: Promise],
modelName: 'Order',
_closed: false,
opts: [Object],
name: 'orders',
collectionName: 'orders',
conn: [NativeConnection],
queue: [],
buffer: false,
emitter: [EventEmitter]
},
collectionName: 'orders'
},
_traceFunction: undefined,
'$useProjection': true
}
But I should return order like this:
{
orders: [
{
"_id":"62693ae3f7fd0b7d87c8eb9c"},
"email":"mohit3#test.com",
"orderId":"1389629752594",
"paymentInfo":"No payment info",
"products":{...},
"address":"adasdklfasflka",
"subtotal":4,
"status":"Paid",
"createdAt":{"$date":"2022-04-27T12:45:23.352Z"},
"updatedAt":{"$date":"2022-04-27T12:45:23.352Z"},"__v":0
},
{
"_id":"62693ae3f7fd0b7d87c8eb9c"},
"email":"mohit3#test.com",
"orderId":"1389629752594",
"paymentInfo":"No payment info",
"products":{...},
"address":"adasdklfasflka",
"subtotal":14,
"status":"Paid",
"createdAt":{"$date":"2022-04-27T12:45:23.352Z"},
"updatedAt":{"$date":"2022-04-27T12:45:23.352Z"},"__v":0
}
]
}
Additionally this is the model schema of Order
const mongoose = require("mongoose");
const OrderSchema = new mongoose.Schema(
{
email: { type: String, required: true },
orderId: { type: String, required: true },
paymentInfo: { type: String, default: "No payment info" },
products: { type: Object, required: true },
address: { type: String, required: true },
subtotal: { type: Number, required: true },
status: { type: String, required: true, default: "Pending" },
},
{ timestamps: true }
);
export default mongoose.models.Order || mongoose.model("Order", OrderSchema);
Please help.
From Model.find(), it returns Query object.
Following the example, you need to execute the query asynchronously.
let mere_orders = await Order.find({email: data.email}).exec();
Or
let mere_orders = await Order.find({email: data.email});
As you are trying to return JSON as:
{
orders: [...]
}
You should return the response as below:
res.status(200).json({ orders: mere_orders });
I have managed to get the connection open to my DB, and to return single records (which took a long time for me to work out how to do!):
MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('payments');
db.collection('general').findOne({ "Physician_Profile_ID" : {$eq: 346085}}, {projection:
{'Physician_Profile_ID': 1,
'Total_Amount_of_Payment_USDollars': 1,
'Physician_First_Name': 1,
'Physician_Last_Name': 1}
}).then(function(doc) {
if(!doc)
throw new Error('No records found!');
console.log('Here is the record: ')
console.log(doc);
});
});
The issue i'm having is that I want to have another call that is able to aggregate the records on the specified physician_profile_id. I want to perform this shell query:
db.general.aggregate
([{$match:{Physician_Profile_ID: 346085}},
{$group:{_id: "$Physician_Profile_ID",
total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}])
How can I translate this into Node.js's dialect? The syntax you use for the Mongo shell isn't translating over
I have tried the following:
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
//var o_id = new ObjectID("5b854c781c332b9558cece8d");
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('payments');
db.collection('general').aggregate({$match:{Physician_Profile_ID: 346085}},{$group:{_id: "$Physician_Profile_ID",
total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}).then(function(doc) {
if(!doc)
throw new Error('No records found!');
console.log('Here is the bastard record: ')
console.log(doc);
});
});
It's throwing this error:
throw err;
^
TypeError: db.collection(...).aggregate(...).then is not a function
at /Users/Badger/mongodb_connect.js:35:67
at result (/Users/Badger/node_modules/mongodb/lib/utils.js:414:17)
at executeCallback (/Users/Badger/node_modules/mongodb/lib/utils.js:406:9)
at err (/Users/Badger/node_modules/mongodb/lib/operations/mongo_client_ops.js:286:5)
at connectCallback (/Users/Badger/node_modules/mongodb/lib/operations/mongo_client_ops.js:241:5)
at process.nextTick (/Users/Badger/node_modules/mongodb/lib/operations/mongo_client_ops.js:463:7)
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickCallback (internal/process/next_tick.js:181:9)
Please can someone help me out, i've been looking for a few hours now and have searched on the site but aren't getting any luck. It's not making sense to me that the error is stating that aggregate isn't a function, when findOne() is. Unless aggregate has to be nested inside of Find(), but this isn't working for me either
Many thanks
Update:
Running this code:
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
//var o_id = new ObjectID("5b854c781c332b9558cece8d");
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('payments');
db.collection('general').aggregate([{$match:{Physician_Profile_ID: 346085}},{$group:{_id: "$Physician_Profile_ID",
total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}], function(err,doc) {
if(err)
throw new Error('No records found!');
console.log('Here is the bastard record: ')
console.log(doc);
});
});
Is returning output that is not expected:
AggregationCursor {
pool: null,
server: null,
disconnectHandler:
Store {
s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: BSON {},
ns: 'payments.general',
cmd:
{ aggregate: 'general',
pipeline: [ [Object], [Object] ],
cursor: {} },
options:
{ readPreference: ReadPreference { mode: 'primary', tags: undefined },
cursor: {},
promiseLibrary: [Function: Promise],
cursorFactory: { [Function: AggregationCursor] super_: [Object], INIT: 0, OPEN: 1, CLOSED: 2 },
disconnectHandler: Store { s: [Object], length: [Getter] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] } },
topology:
Server {
domain: null,
_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 v8.12.0, LE' },
s:
{ coreTopology: [Object],
sCapabilities: [Object],
clonedOptions: [Object],
reconnect: true,
emitError: true,
poolSize: 5,
storeOptions: [Object],
store: [Object],
host: 'localhost',
port: 27017,
options: [Object],
sessionPool: [Object],
sessions: [],
promiseLibrary: [Function: Promise] } },
cursorState:
{ cursorId: null,
cmd: { aggregate: 'general', pipeline: [Array], cursor: {} },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
reconnect: true },
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,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ maxTimeMS: null,
state: 0,
streamOptions: {},
bson: BSON {},
ns: 'payments.general',
cmd: { aggregate: 'general', pipeline: [Array], cursor: {} },
options:
{ readPreference: [Object],
cursor: {},
promiseLibrary: [Function: Promise],
cursorFactory: [Object],
disconnectHandler: [Object],
topology: [Object] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] },
topologyOptions:
{ host: 'localhost',
port: 27017,
disconnectHandler: [Object],
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
monitorCommands: false,
socketOptions: {},
socketTimeout: 360000,
connectionTimeout: 30000,
promiseLibrary: [Function: Promise],
clientInfo: [Object],
read_preference_tags: null,
readPreference: [Object],
dbName: 'admin',
servers: [Array],
server_options: [Object],
db_options: [Object],
rs_options: [Object],
mongos_options: [Object],
socketTimeoutMS: 360000,
connectTimeoutMS: 30000,
bson: BSON {} },
promiseLibrary: [Function: Promise],
session: undefined },
sortValue: undefined }
You have to use db.collection('general').aggregate([{}])
when you do .aggregate it will return you a cursor, and with the cursor you can loop cursor.each but what you want to do most of the cases is to transform it into an array.
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('payments');
db.collection('general').aggregate([{$match:{Physician_Profile_ID: 346085}},{$group:{_id: "$Physician_Profile_ID",
total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}]).toArray(function(err,doc) {
if(err)
throw new Error('No records found!');
console.log('Here is the bastard record: ')
console.log(doc);
});
});
So I am running a legacy $near search here
SoundSpot.find(
{ location : { $near : [ longitude, latitude ], $maxDistance: 100 } }
);
But I'm confused on what is actually happening to what I'm finding. To my understanding and research the search will show the documents sorted by location nearest to the given coordinates, but anything that i do to try to see the documents only outputs this large Query. i have no idea what this giant Query means, im not vary familiar with mongo and javascript and i am trying to figure out how exactly i see what the $near did.
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: Collection { s: [Object] },
opts:
{ bufferCommands: true,
capped: false,
'$wasForceClosed': undefined },
name: 'soundspots',
collectionName: 'soundspots',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: null,
pass: null,
name: 'user_account',
options: null,
otherDbs: [],
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
_connectionOptions: [Object],
'$initialConnection': [Object],
db: [Object],
client: [Object] },
queue: [],
buffer: false,
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },
model:
{ [Function: model]
hooks: Kareem { _pres: [Object], _posts: [Object] },
base:
Mongoose {
connections: [Object],
models: [Object],
modelSchemas: [Object],
options: [Object],
_pluralize: [Function: pluralize],
plugins: [Object] },
modelName: 'soundspot',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: null,
pass: null,
name: 'user_account',
options: null,
otherDbs: [],
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
_connectionOptions: [Object],
'$initialConnection': [Object],
db: [Object],
client: [Object] },
discriminators: undefined,
'$appliedMethods': true,
authenticate: [Function],
serializeUser: [Function],
deserializeUser: [Function],
register: [Function],
findByUsername: [Function],
createStrategy: [Function],
'$appliedHooks': true,
schema:
Schema {
obj: [Object],
paths: [Object],
aliases: {},
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: [Object],
inherits: {},
callQueue: [],
_indexes: [],
methods: [Object],
statics: [Object],
tree: [Object],
query: {},
childSchemas: [],
plugins: [Object],
s: [Object],
_userProvidedOptions: undefined,
options: [Object],
'$globalPluginsApplied': true },
collection:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'soundspots',
collectionName: 'soundspots',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
'$init': Promise { [Object], catch: [Function] } },
schema:
Schema {
obj:
{ name: [Function: String],
key: [Function: String],
connected: [Object],
type: [Object],
location: [Object],
playlist: [Object] },
paths:
{ name: [Object],
key: [Object],
'connected.username': [Object],
type: [Object],
'location.type': [Object],
'location.coordinates': [Object],
'location.longitude': [Object],
'location.latitude': [Object],
'playlist.title': [Object],
'playlist.file': [Object],
'playlist.votes': [Object],
_id: [Object],
username: [Object],
hash: [Object],
salt: [Object],
__v: [Object] },
aliases: {},
subpaths: {},
virtuals: { id: [Object] },
singleNestedPaths: {},
nested: { connected: true, location: true, playlist: true },
inherits: {},
callQueue: [],
_indexes: [],
methods:
{ setPassword: [Function],
changePassword: [Function],
authenticate: [Function] },
statics:
{ authenticate: [Function],
serializeUser: [Function],
deserializeUser: [Function],
register: [Function],
findByUsername: [Function],
createStrategy: [Function] },
tree:
{ name: [Function: String],
key: [Function: String],
connected: [Object],
type: [Object],
location: [Object],
playlist: [Object],
_id: [Object],
username: [Object],
hash: [Object],
salt: [Object],
__v: [Function: Number],
id: [Object] },
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
s: { hooks: [Object] },
_userProvidedOptions: undefined,
options:
{ typeKey: 'type',
id: true,
noVirtualId: false,
_id: true,
noId: false,
validateBeforeSave: true,
read: null,
shardKey: null,
autoIndex: null,
minimize: true,
discriminatorKey: '__t',
versionKey: '__v',
capped: false,
bufferCommands: true,
strict: true,
pluralization: true },
'$globalPluginsApplied': true },
op: 'find',
options: {},
_conditions:
{ location: { '$near': [Object], '$maxDistance': 100 },
_mongooseOption: 'find' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
NodeCollection {
collection:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'soundspots',
collectionName: 'soundspots',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
collectionName: 'soundspots' },
_traceFunction: undefined }
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: Collection { s: [Object] },
opts:
{ bufferCommands: true,
capped: false,
'$wasForceClosed': undefined },
name: 'soundspots',
collectionName: 'soundspots',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: null,
pass: null,
name: 'user_account',
options: null,
otherDbs: [],
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
_connectionOptions: [Object],
'$initialConnection': [Object],
db: [Object],
client: [Object] },
queue: [],
buffer: false,
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },
model:
{ [Function: model]
hooks: Kareem { _pres: [Object], _posts: [Object] },
base:
Mongoose {
connections: [Object],
models: [Object],
modelSchemas: [Object],
options: [Object],
_pluralize: [Function: pluralize],
plugins: [Object] },
modelName: 'soundspot',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: null,
pass: null,
name: 'user_account',
options: null,
otherDbs: [],
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
_connectionOptions: [Object],
'$initialConnection': [Object],
db: [Object],
client: [Object] },
discriminators: undefined,
'$appliedMethods': true,
authenticate: [Function],
serializeUser: [Function],
deserializeUser: [Function],
register: [Function],
findByUsername: [Function],
createStrategy: [Function],
'$appliedHooks': true,
schema:
Schema {
obj: [Object],
paths: [Object],
aliases: {},
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: [Object],
inherits: {},
callQueue: [],
_indexes: [],
methods: [Object],
statics: [Object],
tree: [Object],
query: {},
childSchemas: [],
plugins: [Object],
s: [Object],
_userProvidedOptions: undefined,
options: [Object],
'$globalPluginsApplied': true },
collection:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'soundspots',
collectionName: 'soundspots',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
'$init': Promise { [Object], catch: [Function] } },
schema:
Schema {
obj:
{ name: [Function: String],
key: [Function: String],
connected: [Object],
type: [Object],
location: [Object],
playlist: [Object] },
paths:
{ name: [Object],
key: [Object],
'connected.username': [Object],
type: [Object],
'location.type': [Object],
'location.coordinates': [Object],
'location.longitude': [Object],
'location.latitude': [Object],
'playlist.title': [Object],
'playlist.file': [Object],
'playlist.votes': [Object],
_id: [Object],
username: [Object],
hash: [Object],
salt: [Object],
__v: [Object] },
aliases: {},
subpaths: {},
virtuals: { id: [Object] },
singleNestedPaths: {},
nested: { connected: true, location: true, playlist: true },
inherits: {},
callQueue: [],
_indexes: [],
methods:
{ setPassword: [Function],
changePassword: [Function],
authenticate: [Function] },
statics:
{ authenticate: [Function],
serializeUser: [Function],
deserializeUser: [Function],
register: [Function],
findByUsername: [Function],
createStrategy: [Function] },
tree:
{ name: [Function: String],
key: [Function: String],
connected: [Object],
type: [Object],
location: [Object],
playlist: [Object],
_id: [Object],
username: [Object],
hash: [Object],
salt: [Object],
__v: [Function: Number],
id: [Object] },
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
s: { hooks: [Object] },
_userProvidedOptions: undefined,
options:
{ typeKey: 'type',
id: true,
noVirtualId: false,
_id: true,
noId: false,
validateBeforeSave: true,
read: null,
shardKey: null,
autoIndex: null,
minimize: true,
discriminatorKey: '__t',
versionKey: '__v',
capped: false,
bufferCommands: true,
strict: true,
pluralization: true },
'$globalPluginsApplied': true },
op: 'find',
options: {},
_conditions:
{ location: { '$near': [Object], '$maxDistance': 100 },
_mongooseOption: 'find' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
NodeCollection {
collection:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'soundspots',
collectionName: 'soundspots',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
collectionName: 'soundspots' },
_traceFunction: undefined }
Whenever you need to apply $geometry queries then don't forget to apply index in your schema like this:
location: {
type: [Number], // <Longitude, Latitude>
index: {
type: '2dsphere',
sparse: false
},
required: true,
},
Without index(2dsphere) you can't use $geoNear and $near in your aggregatation.
For ex:
db.places.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
//coordinates: [longitude, latitude]
distanceField: "dist.calculated",
maxDistance: 200, //Meters
includeLocs: "dist.location",
num: 5,
spherical: true
}
}
]);
In above code near find the nearest place from coordinates you requested.
distanceField find the distance in meters and display like this:
"dist" : {
"calculated" : 42107.6268114667, //Meters
"location" : [
-74.167457,
40.3650877
]
}
maxDistance allows you to find location in range of specified distance in meteres.
num is like $limit you can restrict how many data will return.
This is because you're printing the value of the Query object, instead of iterating on the result.
You are using Mongoose, but the issue is the same if you're using the native node driver.
For example, if I have one document in my test collection:
> db.test.find()
{ "_id": 0, "a": 1, "b": 1, "c": 1, "d": 1 }
Now if I run this following code, it will have a similar output to what you saw:
MongoClient.connect('mongodb://localhost:27017/test', (err, db) => {
db.db('test').collection('test').find({}, function(err, res) {
console.log(res);
});
});
Note that in the code above, I'm printing the res object. The output of the code is:
Cursor {
pool: null,
server: null,
disconnectHandler:
Store {
s: { storedOps: [], storeOptions: [Object], topology: [Server] },
length: [Getter] },
bson: BSON {},
ns: 'test.test',
cmd:
{ find: 'test.test',
limit: 0,
skip: 0,
query: {},
readPreference: ReadPreference { mode: 'primary', tags: undefined, options: undefined },
slaveOk: true },
options:
{ readPreference: ReadPreference { mode: 'primary', tags: undefined, options: undefined },
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
db:
.... many more lines ....
The difference is that instead of a Query object, I see the Cursor object.
Now if I iterate on the res:
MongoClient.connect('mongodb://localhost:27017/test', (err, db) => {
db.db('test').collection('test').find({}, function(err, res) {
res.forEach(doc => {console.log(doc)});
});
});
It will print the actual document:
{ _id: 0, a: 1, b: 1, c: 1, d: 1 }
Check out Mongoose's page on the Query object for examples in Mongoose.
I'm new to node.js and mongo, and I'm trying to use findOne() to retrieve an object from the "quizzes" collection of my database so that I can examine its properties.
I know that the object exists, because in the Mongo shell, a findOne() call gives me this:
> db.quizzes.findOne({ quiz_id:1 })
{
"_id" : ObjectId("5564b0bf28b816e2462b6a1a"),
"quiz_id" : 1
}
In my routes/index.js, I have this:
router.post('/submitanswer', function(req, res) {
var db = req.db;
var quizCollection = db.get('quizzes');
var quiz = quizCollection.findOne({ quiz_id: 1 });
}
A console.log(quizCollection) gives:
{ manager:
{ driver:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_connect_args: [Object] },
helper: { toObjectID: [Function], isObjectID: [Function], id: [Object] },
collections: { quizzes: [Circular] },
options: { safe: true },
_events: {} },
driver:
{ _construct_args: [],
_native:
{ domain: null,
_events: {},
_maxListeners: undefined,
databaseName: 'quizzr',
serverConfig: [Object],
options: [Object],
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
native_parser: false,
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: 1432673566484,
eventHandlers: [Object],
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: [Object] },
_emitter: { domain: null, _events: {}, _maxListeners: 50 },
_state: 2,
_connect_args: [ 'mongodb://localhost:27017/quizzr', [Object] ] },
helper:
{ toObjectID: [Function],
isObjectID: [Function],
id:
{ [Function: ObjectID]
index: 847086,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] } },
name: 'quizzes',
col:
{ _construct_args: [],
_native:
{ db: [Object],
collectionName: 'quizzes',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: [Object],
pkFactory: [Object],
serverCapabilities: undefined },
_emitter: { domain: null, _events: {}, _maxListeners: Infinity },
_state: 2,
_skin_db:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_connect_args: [Object] },
_collection_args: [ 'quizzes', undefined ],
id:
{ [Function: ObjectID]
index: 847086,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] },
emitter: { domain: null, _events: {}, _maxListeners: Infinity } },
options: {} }
while a console.log(quiz) gives:
{ col:
{ manager:
{ driver: [Object],
helper: [Object],
collections: [Object],
options: [Object],
_events: {} },
driver:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_connect_args: [Object] },
helper: { toObjectID: [Function], isObjectID: [Function], id: [Object] },
name: 'quizzes',
col:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_skin_db: [Object],
_collection_args: [Object],
id: [Object],
emitter: [Object] },
options: {} },
type: 'findOne',
opts: { quiz_id: 1, name: 1, fields: {}, safe: true },
domain: null,
_events: { error: [Function], success: [Function] },
_maxListeners: undefined,
emitted: {},
ended: false,
success: [Function],
error: [Function],
complete: [Function],
resolve: [Function],
fulfill: [Function],
reject: [Function],
query: { quiz_id: 1 } }
and of course, trying to reference any property of quiz (ex. quiz('quiz_id')) is undefined.
quizCollection.insert() seems to successfully insert an object, so I think I'm getting the right collection. I thought findOne() would return either undefined if it didn't find anything, or an object that fits the criteria, but what I'm printing doesn't seem to be either. How can I retrieve an object?
NodeJS is asynchronous. Some APIs are synchronous, but findOne is an asynchronous one.
findOne has as no return value. You'll get the result passed on your callback. Most APIs return an error as the first argument, which would be undefined if there wasn't an error, and the result of your query/ fs operation/ net operation etc.
Example:
quiz.findOne({quiz_id: 1}, function (err, quiz) {});
This test shows how to query. here
thanks in advance for your time and answers:
I've been trying to do something that "should" be easy but it's being me crazy.
the objective is to asign the result of a function to a variable that i can use later on a POST to send information to my MongoDB.
I've a model with a document as:
{ "__v" : 0, "_id" : ObjectId("54ad1aa637ce5c566c13d18f"), "num" : 9 }
What i want is to capture this number "num" : 9 to a variable. I created a function that query the mongodb through the model.
function getNum(){
var Num = require('./models/num.js');
var callback = function(){
return function(err, data) {
if(err) {
console.log("error found: " + err);
}
console.log("the number is: " + data.num);
}
};
return Num.findOne({}, callback());
};
then just to test i assign that function to a variable and try to console.log it just to test if the result is fine.
// =====================================
// TESTING ==============================
// =====================================
app.get('/testing',function(req, res, next){
var a = getNum();
console.log(a);
});
My output is:
{ _mongooseOptions: {},
mongooseCollection:
{ collection:
{ db: [Object],
collectionName: 'num',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
pkFactory: [Object],
serverCapabilities: undefined },
opts: { bufferCommands: true, capped: false },
name: 'num',
conn:
{ base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'project',
options: [Object],
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: true,
_events: {},
db: [Object] },
queue: [],
buffer: false },
model:
{ [Function: model]
base:
{ connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: [Object] },
modelName: 'Num',
model: [Function: model],
db:
{ base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'project',
options: [Object],
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: true,
_events: {},
db: [Object] },
discriminators: undefined,
schema:
{ paths: [Object],
subpaths: {},
virtuals: [Object],
nested: {},
inherits: {},
callQueue: [Object],
_indexes: [],
methods: {},
statics: {},
tree: [Object],
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
options: [Object],
_events: {} },
options: undefined,
collection:
{ collection: [Object],
opts: [Object],
name: 'num',
conn: [Object],
queue: [],
buffer: false } },
op: 'findOne',
options: {},
_conditions: {},
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
{ collection:
{ collection: [Object],
opts: [Object],
name: 'num',
conn: [Object],
queue: [],
buffer: false } },
_castError: null }
**the number is: 9**
This is one of the results i can get in other aproaches i get undefined.
Can anyone wonder what can i do to solve this?
Again thanks for your help.
You can't return the result of an asynchronous function like findOne, you need to use callbacks.
So it would need to be rewritten as something like:
function getNum(callback){
var Num = require('./models/num.js');
return Num.findOne({}, callback);
};
app.get('/testing',function(req, res, next){
getNum(function(err, a) {
console.log(a);
});
});