MongoDB, find() result, convert to json - json

email: {"email":"aaa#bbb.eu"}
{ _mongooseOptions: {},
mongooseCollection:
{ collection:
{ db: [Object],
collectionName: 'parties',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
pkFactory: [Object],
serverCapabilities: undefined },
opts: { bufferCommands: true, capped: false },
name: 'parties',
conn:
{ base: [Object],
collections: [Object],
models: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'pluserDB',
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: 'Party',
model: [Function: model],
db:
{ base: [Object],
collections: [Object],
models: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'pluserDB',
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: [],
_indexes: [],
methods: {},
statics: {},
tree: [Object],
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
options: [Object],
_events: {} },
options: undefined,
collection:
{ collection: [Object],
opts: [Object],
name: 'parties',
conn: [Object],
queue: [],
buffer: false } },
op: 'find',
options: {},
_conditions: { email: '{"email":"aaa#bbb.eu"}' },
_fields: { email: 1, _id: 0 },
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
{ collection:
{ collection: [Object],
opts: [Object],
name: 'parties',
conn: [Object],
queue: [],
buffer: false },
collectionName: undefined },
_traceFunction: undefined,
_castError: null }
Please have a look at code below:
var parties = Party.find({ email: email }, { email: 1, _id: 0 });
this query returns 3 documents.
Now I want to send result and stringify these documents:
response.json(parties);
I get error here because parties contains circular references and does not just contain plain data I need here.
Question is:
How can I stringify result of find() method here?

I know what my mistake was.
MongoDB and it's shell is not the same as Mongoose API.
find() method needs different arguments for both.
The one I needed here is:
Party.find({ 'email': email }, 'email', function (err, parties) { response.json(parties)});

Related

Parsing aws-clite-gateway-api response issue

Here is my JSON response. I want to parse the below JSON and get Site_id from header.location. I am able to get Status, Message values but not location value.
It is actually response header, I am trying to parse.
Please, anyone can help here?
var apigClientFactory = require('aws-api-gateway-client').default;
let awsbody = JSON.parse(process.argv[2].split('\\').join('') || '{}');
var apigClient = apigClientFactory.newClient({
invokeUrl: awsbody.endPoint, // REQUIRED
accessKey: awsbody.awsAccessKey, // REQUIRED
secretKey: awsbody.awsSecreteKey, // REQUIRED
region: awsbody.awsRegion, // REQUIRED: The region where the AapiKeyloyed.
retryCondition: (err) => { // OPTIONAL: Callback to further control if request should be retried. Uses axon-
retry plugin.
return err.response && err.response.status === 500;
}
});
var pathParams = awsbody.awsPathParams;
// Template syntax follows url-template https://www.npmjs.com/package/url-template
var pathTemplate = awsbody.awsPathTemplate; // '/api/v1/sites'
var method = awsbody.method; // 'POST';
var additionalParams = awsbody.awsAdditionalParams; //queryParams & Headers if any
//var additionalParams = {headers: { "x-apigw-api-id": 'vs2i50xvo4'}};
var body = awsbody.requestBody;
var output = {};
apigClient.invokeApi(pathParams, pathTemplate, method, additionalParams, body)
.then(function(result) {
console.log(result)
}).catch(function(result) {
console.log(result)
});
Here is output: But I just need Status, StatusText, location under headers and data (# bottom) as output. I am tried to parse the output in above code no luck.
Can anyone help to parse response.
{ status: 202,
statusText: 'Accepted',
headers:
{ server: 'Server',
date: 'Tue, 12 Mar 2019 20:34:36 GMT',
'content-type': 'application/json',
'content-length': '61',
'x-amzn-requestid': '400377cd-4506-11e9-b941-3984677a719c',
'x-amz-apigw-id': 'WciqVH8pPHcFgWg=',
location:
'/transit-connectivity/api/v1/jobs/8125d985-3d90-473d-b799-c9974
'x-amzn-trace-id': 'Root=1-5c8817db-5522b10bf2068ac2509ae35b;Samp
connection: 'close' },
config:
{ adapter: [Function: httpAdapter],
transformRequest: { '0': [Function: transformRequest] },
transformResponse: { '0': [Function: transformResponse] },
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers:
{ Accept: 'application/json',
'Content-Type': 'application/json',
'x-apigw-api-id': 'vs2i50xvo4',
'x-amz-date': '20190312T203427Z',
Authorization:
'AWS4-HMAC-SHA256 Credential=AKIAJ4Y5DGRDNBQ2HBYA/20190312/us
cept;content-type;host;x-amz-date;x-apigw-api-id, Signature=801d0887fd
a249',
'User-Agent': 'axios/0.18.0',
'Content-Length': 245 },
method: 'post',
data:
'{"site_id":"TDCLOUDTSTTD03","account_id":"109443356002","change
ider":"aws","region":"us-west-2","network_id":"vpc-0ab26280d5060105c",
01.128/25"]}',
url:
'https://vpce-09d3e2325f36b5527-8xogk1r2.execute-api.us-west-2.v
ites' },
request:
ClientRequest {
_events:
[Object: null prototype] {
socket: [Function],
abort: [Function],
aborted: [Function],
error: [Function],
timeout: [Function],
prefinish: [Function: requestOnPrefinish] },
_eventsCount: 6,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername:
'vpce-09d3e2325f36b5527-8xogk1r2.execute-api.us-west-2.vpce.a
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 8,
connecting: false,
_hadError: false,
_handle: [TLSWrap],
_parent: null,
_host:
'vpce-09d3e2325f36b5527-8xogk1r2.execute-api.us-west-2.vpce.a
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 6,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object] },
connection:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername:
'vpce-09d3e2325f36b5527-8xogk1r2.execute-api.us-west-2.vpce.a
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 8,
connecting: false,
_hadError: false,
_handle: [TLSWrap],
_parent: null,
_host:
'vpce-09d3e2325f36b5527-8xogk1r2.execute-api.us-west-2.vpce.a
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 6,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object] },
_header:
'POST /qa/transit-connectivity/api/v1/sites HTTP/1.1\r\nAccept:
\r\nx-apigw-api-id: vs2i50xvo4\r\nx-amz-date: 20190312T203427Z\r\nAuth
DNBQ2HBYA/20190312/us-west-2/execute-api/aws4_request, SignedHeaders=a
Signature=801d0887fd4a8b86a1af51a02cede529962fc5cae84f4a10f23983100e0
h: 245\r\nHost: vpce-09d3e2325f36b5527-8xogk1r2.execute-api.us-west-2.
_onPendingData: [Function: noopPendingOutput],
agent:
Agent {
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
maxCachedSessions: 100,
_sessionCache: [Object] },
socketPath: undefined,
timeout: undefined,
method: 'POST',
path: '/qa/transit-connectivity/api/v1/sites',
_ended: true,
res:
IncomingMessage {
_readableState: [ReadableState],
readable: false,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
socket: [TLSSocket],
connection: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Array],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 202,
statusMessage: 'Accepted',
client: [TLSSocket],
_consuming: true,
_dumped: false,
req: [Circular],
responseUrl:
'https://vpce-09d3e2325f36b5527-8xogk1r2.execute-api.us-west-
1/sites',
redirects: [] },
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable:
Writable {
_writableState: [WritableState],
writable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 245,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [Circular],
_currentUrl:
'https://vpce-09d3e2325f36b5527-8xogk1r2.execute-api.us-west-
1/sites' },
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]:
[Object: null prototype] {
accept: [Array],
'content-type': [Array],
'x-apigw-api-id': [Array],
'x-amz-date': [Array],
authorization: [Array],
'user-agent': [Array],
'content-length': [Array],
host: [Array] } },
data: { status: 'success', message: 'request has been accepted' } }
varible result is not in json format actually, take a look at my code which is in valid Json format.
You can get location as you need now.
let v = '{"data": {"status": "sucess","message": "request has been accepted"},"responsecode": 202,"responsetext": "Accepted","headers": {"server": "Server","date": "Tue, 12 Mar 2019 20:34:36 GMT","content-type": "application/json","content-length": "61","x-amzn-requestid": "400377cd-4506-11e9-b941-3984677a719c","x-amz-apigw-id": "WciqVH8pPHcFgWg=","location": "/transit-connectivity/api/v1/jobs/8125d985-3d90-473d-b799-c9974","x-amzn-trace-id": "Root=1-5c8817db-5522b10bf2068ac2509ae35b;Sampled=0","connection": "close"}}';
let value = JSON.parse(v);
console.log("location :"value.headers.location);
Console:
location : /transit-connectivity/api/v1/jobs/8125d985-3d90-473d-b799-c9974

Sequelize model prototype show add function, but fails when executed

I am having trouble adding users to my boards model using sequelize. My associations are defined as follows:
module.exports = function(sequelize, DataTypes) {
var Board = sequelize.define("Board", {
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
},
favorited: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
}
});
Board.associate = function(models) {
Board.belongsTo(models.User, {
foreignKey: {
name: "OwnerId"
}
});
Board.belongsToMany(models.User, {
through: "UserBoards"
});
};
return Board;
};
And my user model:
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
isAlphanumeric: true
}
},
email: {
type: DataTypes.STRING,
allowNull: false,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
}
});
User.associate = function(models) {
User.belongsToMany(models.Board, {
through: "UserBoards"
});
};
return User;
};
Console logging Boards.prototype gives me the following:
Board {
_customGetters: {},
_customSetters: {},
validators: { name: { len: [Object] } },
_hasCustomGetters: 0,
_hasCustomSetters: 0,
rawAttributes:
{ id:
{ type: [Object],
allowNull: false,
primaryKey: true,
autoIncrement: true,
_autoGenerated: true,
Model: Board,
fieldName: 'id',
_modelAttribute: true,
field: 'id' },
name:
{ type: [Object],
allowNull: false,
validate: [Object],
Model: Board,
fieldName: 'name',
_modelAttribute: true,
field: 'name' },
favorited:
{ type: BOOLEAN {},
allowNull: false,
defaultValue: false,
Model: Board,
fieldName: 'favorited',
_modelAttribute: true,
field: 'favorited' },
createdAt:
{ type: [Object],
allowNull: false,
_autoGenerated: true,
Model: Board,
fieldName: 'createdAt',
_modelAttribute: true,
field: 'createdAt' },
updatedAt:
{ type: [Object],
allowNull: false,
_autoGenerated: true,
Model: Board,
fieldName: 'updatedAt',
_modelAttribute: true,
field: 'updatedAt' },
OwnerId:
{ name: 'OwnerId',
type: [Object],
allowNull: true,
references: [Object],
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
Model: Board,
fieldName: 'OwnerId',
_modelAttribute: true,
field: 'OwnerId' } },
attributes: [ 'id', 'name', 'favorited', 'createdAt', 'updatedAt', 'OwnerId' ],
_isAttribute: { [Function: memoized] cache: MapCache { size: 0, __data__: [Object] } },
getUser: [Function],
setUser: [Function],
createUser: [Function],
getUsers: [Function],
countUsers: [Function],
hasUser: [Function],
hasUsers: [Function],
setUsers: [Function],
addUser: [Function],
addUsers: [Function],
removeUser: [Function],
removeUsers: [Function] }
But when I try to runt he following in my routes it says that addUser/addUsers are not functions:
router.get("/boards/:id/users/:uid", function(req, res) {
var query = {};
if (req.params.id) {
query.id = req.params.id;
db.Board.findAll({
where: query
}).then(function(dbBoard) {
dbBoard.addUser(req.params.uid);
res.json(dbBoards);
});
}
});
Any help would be appreciated. Thank you.
Adding an association is instance specific. You have to call this method on a single instance of the Board model. For example:
const singleBoard = db.board.findOne({where: query};
const user = db.users.findOne({where: {id: parseInt(req.params.uid)});
singleBoard.addUser(user);
You can iterate through the array you get from querying through findAll if you have to do the same operation on multiple boards.
https://sequelize.org/master/manual/advanced-many-to-many.html

How to get result of nodejs https.get result in json?

The url https://mobileapp.mydomain.com/api/uuids?filter[where][uuid]=02644da038b37d7ba70b7ee1a92ba1d9output is
[{"uuid":"02644da038b37d7ba70b7ee1a92ba1d9","date":"2017/10/05","time":"8:31:41","verified":false,"token":"null","id":"59d5bcb52f416812b0fc817a"}]
In following code https.get's result is not json like and process.stdout.write(d)?
How can I get output in json format with less process.
const https = require('https');
var URL = 'https://mobileapp.mydomain.com/api/uuids?filter[where][uuid]=02644da038b37d7ba70b7ee1a92ba1d9';
https.get(URL, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
}).on('error', (e) => {
console.error('ERROR:',e);
});
update output
output of process.stdout.write(d); :
ClientRequest {
domain:
Domain {
domain: null,
_events: { error: [Function: debugDomainError] },
_eventsCount: 1,
_maxListeners: undefined,
members: [] },
_events:
{ response: { [Function: bound onceWrapper] listener: [Function] },
socket: { [Function: bound onceWrapper] listener: [Function: onSocket] },
error: [Function] },
_eventsCount: 3,
_maxListeners: undefined,
output: [ 'GET /api/uuids?filter[where][uuid]=02644da038b37d7ba70b7ee1a92ba1d9 HTTP/1.1\r\nHost: mobileapp.mydomain.com\r\nConnection: close\r\n\r\n' ],
outputEncodings: [ 'latin1' ],
outputCallbacks: [ [Function: bound onFinish] ],
outputSize: 128,
writable: false,
_last: true,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: null,
connection: null,
_header: 'GET /api/uuids?filter[where][uuid]=02644da038b37d7ba70b7ee1a92ba1d9 HTTP/1.1\r\nHost: mobileapp.mydomain.com\r\nConnection: close\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent:
Agent {
domain:
Domain {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
members: [] },
_events: { free: [Function] },
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: { path: null },
requests: {},
sockets: { 'mobileapp.mydomain.com:443:::::::::': [Array] },
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
maxCachedSessions: 100,
_sessionCache: { map: {}, list: [] } },
socketPath: undefined,
timeout: undefined,
method: 'GET',
path: '/api/uuids?filter[where][uuid]=02644da038b37d7ba70b7ee1a92ba1d9',
_ended: false,
res: null,
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
[Symbol(outHeadersKey)]: { host: [ 'Host', 'mobileapp.mydomain.com' ] } }
> statusCode: 200
headers: { server: 'nginx/1.13.5',
date: 'Thu, 05 Oct 2017 12:43:58 GMT',
'content-type': 'application/json; charset=utf-8',
'content-length': '146',
connection: 'close',
vary: 'Accept-Encoding, Origin, Accept-Encoding',
'access-control-allow-credentials': 'true',
'x-xss-protection': '1; mode=block',
'x-frame-options': 'DENY',
'strict-transport-security': 'max-age=0; includeSubDomains, max-age=31536000',
'x-download-options': 'noopen',
'x-content-type-options': 'nosniff',
etag: 'W/"92-jcLXCzK/YpUyGdSTWS1c4YsxlvU"' }
[{"uuid":"02644da038b37d7ba70b7ee1a92ba1d9","date":"2017/10/05","time":"8:31:41","verified":false,"token":"null","id":"59d5bcb52f416812b0fc817a"}]>

Doing a proper MongoDB Query (TypeError: Converting circular structure to JSON)

I am querying something that I have done multiple times. Take a look, I can't seem to understand.
/* GET all things */
app.get('/things', function(req, res) {
var search = req.query.search;
console.log(search); //works properly and prints strings
Thing.find({ name: {$regex : search}}, function(err, val) {
if(err) throw error;
console.log(val); // returns some horrible JSON
res.send(JSON.stringify(val)); // Throws TypeError
});
})
I thought maybe my query was wrong and that perhaps maybe it's the Mongo shell throwing issues, but when I went into the Mongo shell.
use dbname
> db.booking.find({name: {$regex: "G"}})
>{ "_id" : ObjectId("58238283565e2c1940b16d48"), "name" : "Go to Lesters"}
This is what happens when I print val.
Readable {
pool: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: 'vectio.booking',
cmd:
{ find: 'vectio.booking',
limit: 0,
skip: 0,
query: { name: [Object] },
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: [Object] } },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: [Object] },
db:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
promiseLibrary: [Function: Promise],
disconnectHandler: { s: [Object], length: [Getter] } },
topology:
EventEmitter {
domain: null,
_events:
{ reconnect: [Function],
reconnectFailed: [Function],
timeout: [Object],
error: [Object],
close: [Function],
destroy: [Object],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
attemptReconnect: [Function],
monitoring: [Function] },
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s:
{ options: [Object],
logger: [Object],
Cursor: [Object],
bson: {},
pool: [Object],
disconnectHandler: [Object],
monitoring: true,
inTopology: false,
monitoringInterval: 5000,
topologyId: -1 },
ismaster:
{ ismaster: true,
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 1000,
localTime: 2016-11-09T20:41:56.152Z,
maxWireVersion: 2,
minWireVersion: 0,
ok: 1 },
lastIsMasterMS: 6,
monitoringProcessId:
Timeout {
_called: false,
_idleTimeout: 5000,
_idlePrev: [Object],
_idleNext: [Object],
_idleStart: 255,
_onTimeout: [Function],
_repeat: null },
initalConnect: false,
wireProtocolHandler: {},
_type: 'server',
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v6.2.1, LE, mongodb-core: 2.0.13' },
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
cursorState:
{ cursorId: null,
cmd:
{ find: 'vectio.booking',
limit: 0,
skip: 0,
query: [Object],
slaveOk: true,
readPreference: [Object] },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined },
logger: { className: 'Cursor' },
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: {},
ns: 'vectio.booking',
cmd:
{ find: 'vectio.booking',
limit: 0,
skip: 0,
query: [Object],
slaveOk: true,
readPreference: [Object] },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [Object],
db: [Object],
promiseLibrary: [Function: Promise],
disconnectHandler: [Object] },
topology:
EventEmitter {
domain: null,
_events: [Object],
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s: [Object],
ismaster: [Object],
lastIsMasterMS: 6,
monitoringProcessId: [Object],
initalConnect: false,
wireProtocolHandler: {},
_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: {},
clientInfo: [Object],
readPreference: [Object],
promiseLibrary: [Function: Promise],
bson: {} },
promiseLibrary: [Function: Promise],
currentDoc: null },
sortValue: undefined }
/home/dilraj/Documents/Vectio/scenario-dilraj/node_modules/mongodb/lib/utils.js:99
process.nextTick(function() { throw err; });
^
TypeError: Converting circular structure to JSON
I am trying to get something like
{
_id: ObjectId("58238283565e2c1940b16d48"),
name: "Go to Lesters"
}
or something similar, as long as it makes sense! I just haven't seen anything like this.
I am using Node's Express JS framework, and the only modules I have are Nodemon, Express, bodyParser and Mongo. Nothing else! Thank you, appreciate the love!
The object you are logging is the Mongo cursor. This can be useful at times but to just get the document that is not what you need.
Thing.find(query).toArray(function(err, result){ ... })
Should just return the documents that match your query.
If you request returns a single object, you can also use
Thing.findOne({ name: {$regex : search}}, function(err, val) {
You can use the same syntax but you need to handle the promise using .then
or use async await

parse a values from json data

Am trying to get values from a json data using node.js
Following is the json data(It is dynamic), it may contains names like tcp,ipp,http,udp,https .here i only displaying tcp and ipp only
sample json
[ { '$':
{ name: 'tcp',
showname: 'tnternet crinting Protocol',
size: '584',
pos: '202' },
field: [ [Object], [Object], [Object], [Object] ] },
{ '$':
{ name: 'ipp',
showname: 'Internet Printing Protocol',
size: '584',
pos: '202' },
field: [ [Object], [Object], [Object], [Object], [Object], [Object] ] } ]
i need to get the details of ipp only .
(any other methods without using sample[1] ,like name =ipp from the json data)
example
{ '$':
{ name: 'ipp',
showname: 'Internet Printing Protocol',
size: '584',
pos: '202' },
field:
[ { '$': [Object] },
{ '$': [Object] },
{ '$': [Object] },
{ '$': [Object], field: [Object] },
{ '$': [Object], field: [Object] },
{ '$': [Object] } ] }
You could do it using lodash as follows:
var result = _.result(_.find(list, { '$': {'name':'ipp'} }), '$');
Plunker:
http://plnkr.co/edit/unh9wZuDCnIETE7EWHmD?p=preview
Lodash:
https://lodash.com/docs#find
You'd have to iterate, and look for the name
var ipp = null;
sample.forEach(function(o) {
if ( o['$'].name === 'ipp' ) {
ipp = o;
return false;
}
});
// ipp === object here
FIDDLE