NodeJS, Mongoose, return variable - javascript

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

Related

MongoDB find() giving wrong object?

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

Only one model in mongoose connection

I logged my connection and got this:
// Connect to Mongo
const promise = mongoose
.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false }) // Adding new mongo url parser
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
console.log(promise);
Here' what is logged:
Promise { <pending> }
NativeConnection {
base: Mongoose {
connections: [ [Circular] ],
models: { user: Model { user } },
modelSchemas: { user: [Schema] },
options: { pluralization: true, [Symbol(mongoose:default)]: true },
_pluralize: [Function: pluralize],
Schema: [Function: Schema] {
reserved: [Object: null prototype],
Types: [Object],
ObjectId: [Function]
},
model: [Function],
plugins: [ [Array], [Array], [Array], [Array], [Array] ]
},
collections: {
users: NativeCollection {
collection: null,
Promise: [Function: Promise],
_closed: false,
opts: [Object],
name: 'users',
collectionName: 'users',
conn: [Circular],
queue: [],
buffer: true,
emitter: [EventEmitter]
}
},
models: { user: Model { user } },
config: { autoIndex: true, useCreateIndex: true, useFindAndModify: false },
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype] {
'0': 'disconnected',
'1': 'connected',
'2': 'connecting',
'3': 'disconnecting',
'99': 'uninitialized',
disconnected: 0,
connected: 1,
connecting: 2,
disconnecting: 3,
uninitialized: 99
},
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
plugins: [],
id: 0,
_listening: false,
_connectionString: 'Sorry, but cannot pass :)',
_connectionOptions: {
useNewUrlParser: true,
useUnifiedTopology: true,
promiseLibrary: [Function: Promise],
driverInfo: { name: 'Mongoose', version: '5.10.3' }
},
client: MongoClient {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
s: {
url: 'sorry, but cannot pass :)',
options: [Object],
promiseLibrary: [Function: Promise],
dbCache: Map {},
sessions: Set {},
writeConcern: undefined,
namespace: [MongoDBNamespace]
},
[Symbol(kCapture)]: false
},
'$initialConnection': Promise { <pending> },
then: [Function],
catch: [Function],
_events: [Object: null prototype] {
open: [Function: bound onceWrapper] { listener: [Function] }
},
_eventsCount: 1
The problem is that I have three models: post, user and message and because of that I cannot for example upload file with multer for message or post. Why is it happening? It cannot be a problem with my cluster, because I have second database on that cluster in other projects that works( which have implemented the same things, but with correct effect).
The only issue I think can be happening with this connection you might be passing a new schema and model that you will see in your object is with that schema. You don't get all schemas from the cloud, the schema being returned is the one that exists with this connection.

How to display the results of MongoDB $near query

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.

Using YQL in Node JS

enter code hereI am trying to extract content out of a website for learning purposes. I used YQL for that and it gave me JSON back(https://developer.yahoo.com/yql/). I thought I was making progress but unfortunately I was not able to get same output via NPM module. Following is my code:
var YQL = require('yql');
new YQL.exec('select * from html where url="http://www.natnlawcenter.com/United-States-Car-Dealerships/Alabama.aspx" ', function(response) {
console.log(response);
});
and following is my output:
{ query:
{ count: 1,
created: '2015-09-27T23:51:25Z',
lang: 'en-US',
results: { body: [Object] } } }
How do I access content of body:[Object]?
Thanks for your time.
I have modified the code as below:
request({
method: 'GET',
url: 'http://www.natlawcenter.com/United-States-Car-Dealerships/Alabama.aspx'
}, function(err, response, body) {
if (err) return console.error(err);
// Tell Cherrio to load the HTML
$ = cheerio.load(body);
console.log($('td').each(function(i, element){
var a = $(this);
console.log(a);
}));
});
and following is my output:
{ options:
{ withDomLvl1: true,
normalizeWhitespace: false,
xmlMode: false,
decodeEntities: true },
_root:
{ '0':
{ type: 'root',
name: 'root',
attribs: {},
children: [Object],
next: null,
prev: null,
parent: null },
options:
{ withDomLvl1: true,
normalizeWhitespace: false,
xmlMode: false,
decodeEntities: true },
length: 1,
_root: [Circular] },
length: 0,
prevObject:
{ options:
{ withDomLvl1: true,
normalizeWhitespace: false,
xmlMode: false,
decodeEntities: true },
_root: { '0': [Object], options: [Object], length: 1, _root: [Circular] },
length: 0,
prevObject: { '0': [Object], options: [Object], length: 1, _root: [Circular] } } }
[Function]
[Function]
[Function]
[Function]
[Function]
{ '0':
{ type: 'tag',
name: 'td',
attribs: { valign: 'top', width: '999' },
children: [ [Object], [Object] ],
next:
{ data: '\r\n\t\t\t\t\t\t\t\t',
type: 'text',
next: null,
prev: [Circular],
parent: [Object] },
prev:
{ data: '\r\n\t\t\t',
type: 'text',
next: [Circular],
prev: null,
parent: [Object] },
parent:
{ type: 'tag',
name: 'tr',
attribs: {},
children: [Object],
next: [Object],
prev: [Object],
parent: [Object] } },
-------------------------------
'188':
{ type: 'tag',
name: 'td',
attribs: { width: '25%', icobalt: 'System.Web.UI.ITemplate' },
children:
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ],
next:
{ type: 'tag',
name: 'td',
attribs: [Object],
children: [Object],
next: [Object],
prev: [Circular],
parent: [Object] },
prev:
{ type: 'tag',
name: 'tr',
attribs: [Object],
children: [Object],
next: [Circular],
prev: [Object],
parent: [Object] },
parent:
{ type: 'tag',
name: 'tbody',
attribs: {},
children: [Object],
next: null,
prev: null,
parent: [Object] } },
How can I access whats in children object of for example '188'?
Thanks for your time.
You need parse the JSON response in to JS object using JSON.parse(). Your code can we re-written like so -
request({
method: 'GET',
url: 'http://www.natlawcenter.com/United-States-Car-Dealerships/Alabama.aspx'
}, function(err, response, body) {
if (err) return console.error(err);
if (response.statusCode === 200 && body) return JSON.parse(body);
});

MongoDB findOne query doesn't return result or undefined

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

Categories