Mongoose find returning odd object - node.js

my current problem is with the db.collection.find() mongoose command. I'm relatively new to mongoose/mongodb, but I've gotten the hang of the concepts of it. Here is the test code I've been trying to run:
mongoose.connect(url);
function main()
{
var db = mongoose.connection;
db.on('open', function() {
db.collection('Tweet').find({id: 631460910368956400}, function (err, data){
console.log(data);
})
/*var coll = db.collection('Tweet');
db.collection('Tweet').findOne({id: 631460910368956400},function (err, ret) {
if(err) console.log(err);
console.log(ret['id']);
//db.close();
});*/
});
}
main();
The data returned from the non commented out field is a strange object:
{ connection: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: 'TEST.Tweet',
cmd: { find: 'TEST.Tweet', limit: 0, skip: 0, query: {}, slaveOk: false },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: false,
db:
{ domain: null,
_events: [Object],
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
etc etc... it goes on for much longer.
The IP address is a remote connection that successfully connects. I can do things like add and remove documents, but cannot actually view the documents from the javascript. I know that it is caused due to some kind of asynchronous problem, however I'm not sure how to fix it. Also, the commented out code for .findOne() seems to pull data completely fine in the code above.
What would be the problem with the code for the .find() function? An explanation for why the current error in data retrieving would be great also.
Thanks for your help!

The object you receive is a Cursor which is an object used to retrieve the actual results.
When you are sure your query will never return more than one object (like in this case where you query by the always unique _id field), you can use db.collection('Tweet').findOne( which will return just that object without the additional layer of indirection.
But when your query can potentially return more than one document, you need to use a cursor. To resolve the cursor, you can turn it into an array of documents by using cursor.toArray:
db.collection('Tweet').find({}, function (err, cursor){
cursor.toArray().forEach(function(doc) {
console.log(doc);
});
})
This is the most simple version. For more information about cursors, refer to the documentation linked above.
By the way: So far you only used the functionality of the native driver. When you want to use Mongoose to query objects, you might want to use the methods of the Mongoose model object.

Related

mongo db data not returned in resolver function for graphql but working in routes of my nodejs server

I am setting up a node js environment based on hapi, graphql and mongodb. I am able to make connection to mongodb and retrieve and display data in the GET/POST routes using db mongoose schemas. But data is not getting retrieved when the model is passed to the resolver function of graphql. Please find below my graphql resolver function
const resolvers = (shows)=>({
myQuery:{
testFunction(){
return "returned from custom test function";
},
getShowByName: function(_,args){
var out= shows.findOne();
console.log(out); //returning a huge json response instead of proper data
return out={
_id:"5349b4ddd2781d08c09890f3",
title: "test",
version: "test",
showDetails: [{
name: args.showSchemaName,
genre: "test",
lead_actor: "test"
}]
}
;
},
},
myMutation: {
createShow: function(_,args){
return args.showTypeInputDetails.title+","+args.showTypeInputDetails.version;
}
}
});
module.exports = resolvers;
Console.log(out) is letting out a huge json response which is not coming from the mongo db. The json response is really huge and also has my connection parameters, credentials and other details, hence, i am posting the beginning of the response here
Query {
_mongooseOptions: {},
_transforms: [],
mongooseCollection:
NativeCollection {
collection: Collection { s: [Object] },
opts:
{ bufferCommands: true,
capped: false,
'$wasForceClosed': undefined },
name: 'shows_details',
collectionName: 'shows_coll',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
Please help me in understanding why this response in coming when the findOne() is triggered from resolvers functions and proper results when the same function is triggered from the routes function.
[shows is my mongoose db model]
why don't you try like below code.
dbo.collection("collection_name").findOne({}, function(err, result) {
if (err) throw err;
console.log(result.name);
db.close();
});
i made my resolver function async, and returned the data with await and that solved the problem

Aerospike Query Error

query = CLIENT.query(NAMESPACE, SET);
stream = query.foreach();
/*
Get list of all avialable keys
*/
stream.on('error', (error) => {
throw error;
});
stream.on('data', (record) => {
console.info('data', record);
console.info('key', record.key.key);
});
stream.on('end', () => {
console.log('done!');
process.exit(0);
});
Receiving error - AerospikeError: Record does not exist in database. May be returned by read, or write with policy Aerospike.policy.exists.UPDATE.
error encountered in promise chain => { [AerospikeError: Record does not exist in database. May be returned by read, or write with policy Aerospike.policy.exists.UPDATE]
name: 'AerospikeError',
code: 2,
command:
QueryCommand {
client:
Client {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
config: [Object],
as_client: AerospikeClient {},
connected: true,
captureStackTraces: false },
args: [ 'sms_data', 'some_set', [Object], undefined ],
captureStackTraces: false,
key: undefined,
stream:
RecordStream {
aborted: false,
client: [Object],
_events: [Object],
_eventsCount: 3 } },
func: 'as_query_parse_records_async',
file: 'src/main/aerospike/aerospike_query.c',
line: 237,
inDoubt: false }
Although the data is present in the namespace and set.
query result :
aql> select * from sms_data.some_set;
+-----------------------------------------------------+----------+
| 0 | name |
+-----------------------------------------------------+----------+
| MAP('{"dummy":[{"x":"dgjasgdj"}], "name":"Vidur"}') | "Khanna" |
+-----------------------------------------------------+----------+
This is a bug in the Aerospike Node.js client (all versions up to and including v3.2.0). The short version is, that this occurs on Query operations, if at least one server node in the cluster does not have any records in the set that you are querying. See issue #253 on GitHub for details. This should get resolved in the next client release.

node-soap - Proper method of calling function

I know absolutely nothing about SOAP lol, But a vital part of my software requires I use it for a particular webservice. The documentation for the webservice was written for .net so it makes it even harder for me to understand what I need to do here. On top of all that they require authentication.
For the connecting I do not need to authorize so I am able to retreive the describe function result. They are as follows:
I20151214-09:20:20.381(-8)? Getting inside soap client creation method
I20151214-09:20:20.722(-8)? Exception while invoking method 'createSoapClient' TypeError: Cannot call method 'describe' of undefined
I20151214-09:20:20.723(-8)? at Object.Soap.createClient (packages/zardak_soap/packages/zardak_soap.js:37:1)
I20151214-09:20:20.724(-8)? at [object Object].Meteor.methods.createSoapClient (controllers/server/testFiles.js:21:1)
I20151214-09:20:20.724(-8)? at maybeAuditArgumentChecks (livedata_server.js:1698:12)
I20151214-09:20:20.725(-8)? at livedata_server.js:708:19
I20151214-09:20:20.725(-8)? at [object Object]._.extend.withValue (packages/meteor/packages/meteor.js:1013:1)
I20151214-09:20:20.726(-8)? at livedata_server.js:706:40
I20151214-09:20:20.726(-8)? at [object Object]._.extend.withValue (packages/meteor/packages/meteor.js:1013:1)
I20151214-09:20:20.726(-8)? at livedata_server.js:704:46
I20151214-09:20:20.727(-8)? at tryCallTwo (C:\Users\Media Center\AppData\Local\.meteor\packages\promise\0.5.1\npm\node_modules\meteor-promise\node_modules\promise\lib\core.js:45:5)
I20151214-09:20:20.727(-8)? at doResolve (C:\Users\Media Center\AppData\Local\.meteor\packages\promise\0.5.1\npm\node_modules\meteor-promise\node_modules\promise\lib\core.js:171:13)
I20151214-09:20:21.996(-8)? Getting inside the return of the create client
I20151214-09:20:22.007(-8)? { PRIMEStandardV1_1:
I20151214-09:20:22.008(-8)? { PRIMEStandardV1_1Soap:
I20151214-09:20:22.009(-8)? { RunTrip: [Object],
I20151214-09:20:22.009(-8)? ReverseGeocode: [Object],
I20151214-09:20:22.010(-8)? FindLocationsInRadius: [Object],
I20151214-09:20:22.010(-8)? FindLocationsOnRoute: [Object],
I20151214-09:20:22.010(-8)? FindLocationsInState: [Object],
I20151214-09:20:22.011(-8)? GetAverageDieselPriceInState: [Object],
I20151214-09:20:22.012(-8)? TestRadiusGeofence: [Object],
I20151214-09:20:22.012(-8)? TestRouteGeofence: [Object],
I20151214-09:20:22.013(-8)? RunSimpleTrip: [Object],
I20151214-09:20:22.013(-8)? Geocode: [Object],
I20151214-09:20:22.014(-8)? GetTodaysUSDieselAverage: [Object],
I20151214-09:20:22.014(-8)? GetTodaysCanadianDieselAverage: [Object],
I20151214-09:20:22.015(-8)? GetTripDistance: [Object],
I20151214-09:20:22.016(-8)? ValidateLocation: [Object] },
I20151214-09:20:22.017(-8)? PRIMEStandardV1_1Soap12:
I20151214-09:20:22.017(-8)? { RunTrip: [Object],
I20151214-09:20:22.018(-8)? ReverseGeocode: [Object],
I20151214-09:20:22.019(-8)? FindLocationsInRadius: [Object],
I20151214-09:20:22.021(-8)? FindLocationsOnRoute: [Object],
I20151214-09:20:22.021(-8)? FindLocationsInState: [Object],
I20151214-09:20:22.022(-8)? GetAverageDieselPriceInState: [Object],
I20151214-09:20:22.022(-8)? TestRadiusGeofence: [Object],
I20151214-09:20:22.023(-8)? TestRouteGeofence: [Object],
I20151214-09:20:22.023(-8)? RunSimpleTrip: [Object],
I20151214-09:20:22.024(-8)? Geocode: [Object],
I20151214-09:20:22.025(-8)? GetTodaysUSDieselAverage: [Object],
I20151214-09:20:22.025(-8)? GetTodaysCanadianDieselAverage: [Object],
I20151214-09:20:22.026(-8)? GetTripDistance: [Object],
I20151214-09:20:22.026(-8)? ValidateLocation: [Object] } } }
caseless:
I20151216-11:53:14.658(-8)? { dict:
I20151216-11:53:14.658(-8)? { 'cache-control': 'private',
I20151216-11:53:14.659(-8)? 'content-type': 'text/xml; charset=utf- 8',
I20151216-11:53:14.659(-8)? server: 'Microsoft-IIS/7.0',
I20151216-11:53:14.660(-8)? 'x-aspnet-version': '4.0.30319',
I20151216-11:53:14.660(-8)? 'x-powered-by': 'ASP.NET',
I20151216-11:53:14.661(-8)? date: 'Wed, 16 Dec 2015 19:40:29 GMT',
I20151216-11:53:14.661(-8)? connection: 'close',
I20151216-11:53:14.662(-8)? 'content-length': '441' } },
I20151216-11:53:14.662(-8)? pipe: [Function],
I20151216-11:53:14.663(-8)? addListener: [Function: addListener],
I20151216-11:53:14.664(-8)? on: [Function: addListener],
I20151216-11:53:14.665(-8)? pause: [Function],
I20151216-11:53:14.665(-8)? resume: [Function],
I20151216-11:53:14.666(-8)? read: [Function],
I20151216-11:53:14.666(-8)? body: 'soap:ServerServer was unable to process request. ---> Object reference not set to an instance of an object.' }
I20151216-11:53:16.716(-8)? Error: [object Object]
I20151216-11:53:16.722(-8)? { Envelope: { Body: { Fault: [Object] } } }
I20151216-11:53:16.723(-8)? undefined
As you can see I am able to connect. Now the part that is trowing me off is to actually call one of these functions. Below is the code I am using to try to call the "RunSimpleTrip". However when I console log the Result it is a huge jumble of messages that end up running the buffer out on my cmd window and I can only see back a little ways none of it making sense.
var url = 'http://prime.promiles.com/Webservices/v1_1/PRIMEStandardV1_1.asmx?wsdl';
var simpleTrip = {
AvoidTollRoads: false,
BorderOpen: true,
RoutingMethod: "PRACTICAL",
TripLegs: [{LocationText: "77611"},
{LocationText: "90210"}]
}
Soap.createClient(url, function(err, client) {
console.log(client.describe());
client.setSecurity(new Soap.BasicAuthSecurity('hoperd', 'mailaaron', 'bkkyt'));
client.PRIMEStandardV1_1.PRIMEStandardV1_1Soap.RunSimpleTrip(simpleTrip, function(err, result, raw, soapHeader) {
//console.log("Result: ");
console.log(result);
console.log("Error: " + err.root);
console.log(err.root);
console.log(soapHeader);
// result is a javascript object
// raw is the raw response
// soapHeader is the response soap header as a javascript object
})
});
From the API's documentation this is how they call the same function using .net
PRIMEEnterpriseV1 PRIME = new PRIMEEnterpriseV1();
//Authorization Credentials
Credentials c = new Credentials();
c.Username = "MyUsername;
c.Password = "MyPassword";
c.CompanyCode ="MyCompanyCode";
SimpleTrip st = new SimpleTrip();
st.AvoidTollRoads = false;
st.BorderOpen = true;
st.RoutingMethod = com.promiles.PRIME.Enterprise.RouteMethod.PRACTICAL;
TripLeg[] Legs = new TripLeg[2];
//Origin
TripLeg t = new TripLeg();
t.LocationText = "77611";
Legs[0] = t;
//Destination
t = new TripLeg();
t.LocationText = "90210";
Legs[1] = t;
st.TripLegs = Legs;
//Call Function
SimpleTrip rt = PRIME.RunSimpleTrip(c, st);
I am hoping someone our there has a clue to this mystery for me or can point me in the right direction as to how to properly connect this this. Any and all help will be greatly appreciated.
So after much trial and error I was able to figure this out. The below code works to call the SimpleTrip and return a proper response from the server. My TripLegs arg still isn't 100% correct to what the SOAP is looking for but the code and the way to call it is.
var url = 'http://prime.promiles.com/Webservices/v1_1/PRIMEStandardV1_1.asmx?wsdl';
var credentials = { Username: "xxxxx",
Password: "xxxxxx",
CompanyCode: "xxxxx"
};
var simpleTrip = {
AvoidTollRoads: false,
BorderOpen: true,
RoutingMethod: "PRACTICAL",
VehicleType: "Tractor2AxleTrailer2Axle",
TripLegs: [{Location: {LocationText: "77611"}},
{Location: {LocationText: "90210"}}]
}
args = {c: credentials, BasicTrip: simpleTrip};
Soap.createClient(url, function(err, client) {
console.log(err);
console.log(simpleTrip);
client.RunSimpleTrip(args, function(err, result, raw, soapHeader) {
console.log(result);
//console.log(err.root);
console.log(err.root.Envelope);
})
});

Get the correct result while executing a find query on mongodb using node

So I am trying to run a nodejs script to make some custom action on a mongo database. The problem I am facing is with the following script -
// a valid id obtained before
collection.find({"id":id}, function(err, result) {
if(err) {
console.log("Could not select");
} else {
console.log("Select successful for id: " + id);
console.log(result);
}
});
Now when I check the result after running this, I only see data about the db, a whole lot of it that is not really concerned with the select query. What I want is what anyone would expect! A list of the documents for that id. Obviously, I am missing something here, could anyone please point me to it?
EDIT:
So when I run the query on the mongo shell, I get the expected result.
db.messages.findOne({"id":"<a random id that has a json inserted in mongo>"})
However, when I run it from the script shown above, all I get is this:
Select successful for id: <random uid from above>
{ db:
{ domain: null,
_events: {},
_maxListeners: 10,
databaseName: 'test',
serverConfig:
{ domain: null,
_events: [Object],
_maxListeners: 10,
_callBackStore: [Object],
_commandsStore: [Object],
auth: [Object],
_dbStore: [Object],
options: [Object],
_serverState: 'connected',
_haProcess: [Object],
servers: [Object],
strategyInstance: [Object],
emitOpen: false,
.....
.....
.....
Thanks
The result parameter that find provides to the callback is a cursor, not an array of results. Call toArray to iterate over the resulting cursor and get an array of docs:
collection.find({"id":id}).toArray(function(err, result) {
if(err) {
console.log("Could not select");
} else {
console.log("Select successful for id: " + id);
console.log(result);
}
});
Or if id uniquely identifies a single doc, use findOne instead:
collection.findOne({"id":id}, function(err, result) {
if(err) {
console.log("Could not select");
} else {
console.log("Select successful for id: " + id);
console.log(result);
}
});

Connected clients in express.io

I'm developing a simple chat app using node.js and express.io
I would like to display a list of the connected clients (or online for chat) all the time.
In express.io's doc, there is no clear way on how to "get" the list of connected clients once a new one has entered the room, i.e there is just the "broadcast" but not the "get".
Have someone done this before?
Any clues will be really helpful.
Thanks!
Edit:
After trying #jibsales's answer. I think we are almost there. What clients returns me is not the actual array of clients but this one:
[ { id: 'OWix3sqoFZAa20NLk304',
namespace:
{ manager: [Object],
name: '',
sockets: [Object],
auth: false,
flags: [Object],
_events: [Object] },
manager:
{ server: [Object],
namespaces: [Object],
sockets: [Object],
_events: [Object],
settings: [Object],
handshaken: [Object],
connected: [Object],
open: [Object],
closed: [Object],
rooms: [Object],
roomClients: [Object],
oldListeners: [Object],
sequenceNumber: 496205112,
router: [Object],
middleware: [],
route: [Function],
use: [Function],
broadcast: [Function],
room: [Function],
gc: [Object] },
disconnected: false,
ackPackets: 0,
acks: {},
flags: { endpoint: '', room: '' },
readable: true,
store: { store: [Object], id: 'OWix3sqoFZAa20NLk304', data: {} },
_events:
{ error: [Function],
ready: [Function],
connection: [Function],
NewChatPrivateLine: [Function],
NewIdea: [Function],
NewChatLine: [Function],
NewPost: [Function] } } ]
The functions are:
var app = require('express.io')();
app.io.route('connection', function(req) {
req.io.join(req.data.room);
var clients = app.io.sockets.clients(req.data.room);
console.log(clients)
app.io.room(req.data.room).broadcast('announce', {
user: req.data.user,
clients: clients
})
});
This actually returns an error ( data = JSON.stringify(ev); TypeError: Converting circular structure to JSON) as the array has several circular objects and hence it cannot be broadcasted.
Any thoughts?
Because express.io is simply glueing express and socket.io, don't forget to look at socket.io's documentation as well. With that said, since socket.io v0.7, we now have an API method to get this information:
var clients = io.sockets.clients('room'); // all users from room `room`
Unfortunately express.io is written in coffeescript (UGGGH!!!) so I'm having a hard time reading the source, but it looks like when you require the express.io module, the socket.io instance is hoisted up as well:
var express = require('express.io');
var clients = express.io.sockets.clients('room'); // all users from room `room`
If this doesn't work, I would ditch express.io for a manual configuration with express and socket.io because it looks like express.io has a VERY opinionated API. Its really not that hard at all as express.io is doing nothing more than creating a pretty interface/abstraction to manual configuration (which is actually hurting you in this use case if the above doesn't work).
I would also checkout SockJS as I (and many other websocket consumers) ditched socket.io for SockJS due to a lack of community support. Not to mention, there is a SEVERE memory leak in IE9 when falling back to xhr-polling.
Well, finally I went with the "tacking" solution proposed by #Brad. It is not the most elegant but, if you can help me improve it, It'd be awesome!!
This is the final code:
Server-side
var app = require('express.io')();
//To broadcast the users online in room sent by the client
var clients = [];
app.io.route('connect', function (req) {
req.io.leave(req.data.room).on('disconnect', function() {
//To remove client from list when disconnected
var index = clients.indexOf(req.data.user);
if (index > -1) {
clients.splice(index, 1);
}
app.io.room(req.data.room).broadcast('announce', {
user: req.data.user,
clients: clients
})
});
req.io.join(req.data.room);
//To avoid repeating the same client with several opened windows/tabs
var index = clients.indexOf(req.data.user);
if (index === -1) {
clients.push(req.data.user);
}
app.io.room(req.data.room).broadcast('announce', {
user: req.data.user,
clients: clients
})
});
Client-side
// Emit ready event with person name and predefined room for who's online
io.emit('connect', {
room: room,
user: user
});
//Get the signal from server and create your list
io.on('announce', function (data){
//Do awesome stuff with data
});

Resources