i've a problem with the following Json :
[ { constant: false,
inputs: [Object],
name: 'set',
outputs: [],
type: 'function'
}, {
constant: true,
inputs: [],
name: 'get',
outputs: [Object],
type: 'function'
}, {
anonymous: false,
inputs: [Object],
name: 'ItBlinks',
type: 'event'
},
set: {
[Function: bound]
request: [Function: bound],
call: [Function: bound],
sendTransaction: [Function: bound],
estimateGas: [Function: bound],
getData: [Function: bound],
uint256: [Circular]
},
get: {
[Function: bound]
request: [Function: bound],
call: [Function: bound],
sendTransaction: [Function: bound],
estimateGas: [Function: bound],
getData: [Function: bound],
'': [Circular]
},
allEvents: [Function: bound],
ItBlinks: {
[Function: bound] uint256: [Function: bound]
}
}
This JSon is the ABI and this should be add to my contract into my wallet (Ethereum Wallet) to send information (in this case, made a blink event on my raspberry PI)
When I add these line into my contract in my ethereum wallet, it tell me my Json is not correct.
I've try to validate, but it give me an error, and i cannot solve it. (I'm a beginner in JSon)
Somebody can help me to validate the get / set method? to be a valid JSon format?
This is the full return with coinbase (the address and coinbase is modified) :
coinbase : 0x20408a19c567a475545947600a95130f24f7C123
{ _eth:
Eth {
_requestManager: { provider: [Object], polls: {}, timeout: null },
getBalance: { [Function] request: [Function: bound ], call: 'eth_getBalance' },
getStorageAt: { [Function] request: [Function: bound ], call: 'eth_getStorageAt' },
getCode: { [Function] request: [Function: bound ], call: 'eth_getCode' },
getBlock: { [Function] request: [Function: bound ], call: [Function] },
getUncle: { [Function] request: [Function: bound ], call: [Function] },
getCompilers: { [Function] request: [Function: bound ], call: 'eth_getCompilers' },
getBlockTransactionCount: { [Function] request: [Function: bound ], call: [Function] },
getBlockUncleCount: { [Function] request: [Function: bound ], call: [Function] },
getTransaction:
{ [Function]
request: [Function: bound ],
call: 'eth_getTransactionByHash' },
getTransactionFromBlock: { [Function] request: [Function: bound ], call: [Function] },
getTransactionReceipt:
{ [Function]
request: [Function: bound ],
call: 'eth_getTransactionReceipt' },
getTransactionCount: { [Function] request: [Function: bound ], call: 'eth_getTransactionCount' },
call: { [Function] request: [Function: bound ], call: 'eth_call' },
estimateGas: { [Function] request: [Function: bound ], call: 'eth_estimateGas' },
sendRawTransaction: { [Function] request: [Function: bound ], call: 'eth_sendRawTransaction' },
signTransaction: { [Function] request: [Function: bound ], call: 'eth_signTransaction' },
sendTransaction: { [Function] request: [Function: bound ], call: 'eth_sendTransaction' },
sign: { [Function] request: [Function: bound ], call: 'eth_sign' },
compile: { solidity: [Object], lll: [Object], serpent: [Object] },
submitWork: { [Function] request: [Function: bound ], call: 'eth_submitWork' },
getWork: { [Function] request: [Function: bound ], call: 'eth_getWork' },
coinbase: [Getter],
getCoinbase: { [Function] request: [Function: bound ] },
mining: [Getter],
getMining: { [Function] request: [Function: bound ] },
hashrate: [Getter],
getHashrate: { [Function] request: [Function: bound ] },
syncing: [Getter],
getSyncing: { [Function] request: [Function: bound ] },
gasPrice: [Getter],
getGasPrice: { [Function] request: [Function: bound ] },
accounts: [Getter],
getAccounts: { [Function] request: [Function: bound ] },
blockNumber: [Getter],
getBlockNumber: { [Function] request: [Function: bound ] },
protocolVersion: [Getter],
getProtocolVersion: { [Function] request: [Function: bound ] },
iban:
{ [Function]
fromAddress: [Function],
fromBban: [Function],
createIndirect: [Function],
isValid: [Function] },
sendIBANTransaction: [Function: bound ] },
transactionHash: null,
address: '0x9535eb707582edb3317dfdcdb365ce4186500C123',
abi:
[ { constant: false,
inputs: [Object],
name: 'set',
outputs: [],
type: 'function' },
{ constant: true,
inputs: [],
name: 'get',
outputs: [Object],
type: 'function' },
{ anonymous: false,
inputs: [Object],
name: 'ItBlinks',
type: 'event' } ],
set:
{ [Function: bound ]
request: [Function: bound ],
call: [Function: bound ],
sendTransaction: [Function: bound ],
estimateGas: [Function: bound ],
getData: [Function: bound ],
uint256: [Circular] },
get:
{ [Function: bound ]
request: [Function: bound ],
call: [Function: bound ],
sendTransaction: [Function: bound ],
estimateGas: [Function: bound ],
getData: [Function: bound ],
'': [Circular] },
allEvents: [Function: bound ],
ItBlinks: { [Function: bound ] uint256: [Function: bound ] }
}
You do not have valid JSON. JSON has key/value pairs with keys being strings delimited by double quotes. Details of JSON can be found here
From the Ethereum documentation this is an example of JSON in the ABI:
[{
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event"
}, {
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event2"
}, {
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event2"
}, {
"type":"function",
"inputs": [{"name":"a","type":"uint256"}],
"name":"foo",
"outputs": []
}]
Details of the ethereum contract ABI can be found here
What you were showing is a payload from coinbase it contains lots of information regarding your request, the smart-contracts ABI is one of them.
In reality it is only
abi:[ { constant: false,
inputs: [Object],
name: 'set',
outputs: [],
type: 'function' },
{ constant: true,
inputs: [],
name: 'get',
outputs: [Object],
type: 'function' },
{ anonymous: false,
inputs: [Object],
name: 'ItBlinks',
type: 'event' } ]
you can access the abi by doing this
coinbase[0x20408a19c567a475545947600a95130f24f7C123].abi
i don't know your exact use case but i suggest you read about smart contracts abis here
I did have the same issue.
The problem is this [Object] inside your JSON
You probably get the ABI from console.log object.
You have to convert this JSON object to a string, and then console.log it and grab the output which will be a valid JSON.
Related
I started to learn how to build Rest API using Nodejs,Expressjs,Sequelize and MySQL using Mysqlworkbench.
My Problem: After I start the server, the table is not created by Sequelize and no table in Mysqlworkbench also. Just this message appeared below... Thanks for any guide or help in advance:-
Sequelize {
options:
{ dialect: 'mysql',
dialectModulePath: null,
host: 'localhost',
protocol: 'tcp',
define: {},
query: {},
sync: {},
timezone: '+00:00',
logging: [Function: bound consoleCall],
omitNull: false,
native: false,
replication: false,
ssl: undefined,
pool: {},
quoteIdentifiers: true,
hooks: {},
retry: { max: 5, match: [Array] },
transactionType: 'DEFERRED',
isolationLevel: null,
databaseVersion: 0,
typeValidation: false,
benchmark: false,
operatorsAliases: false },
config:
{ database: 'node',
username: 'root',
password: '1234567890',
host: 'localhost',
port: 3306,
pool: {},
protocol: 'tcp',
native: false,
ssl: undefined,
replication: false,
dialectModulePath: null,
keepDefaultTimezone: undefined,
dialectOptions: undefined },
dialect:
MysqlDialect {
sequelize: [Circular],
connectionManager:
ConnectionManager {
sequelize: [Circular],
config: [Object],
dialect: [Circular],
versionPromise: null,
dialectName: 'mysql',
pool: [Object],
lib: [Object] },
QueryGenerator:
{ dialect: 'mysql',
OperatorMap: [Object],
createSchema: [Function: createSchema],
showSchemasQuery: [Function: showSchemasQuery],
versionQuery: [Function: versionQuery],
createTableQuery: [Function: createTableQuery],
showTablesQuery: [Function: showTablesQuery],
addColumnQuery: [Function: addColumnQuery],
removeColumnQuery: [Function: removeColumnQuery],
changeColumnQuery: [Function: changeColumnQuery],
renameColumnQuery: [Function: renameColumnQuery],
handleSequelizeMethod: [Function: handleSequelizeMethod],
_toJSONValue: [Function: _toJSONValue],
upsertQuery: [Function: upsertQuery],
deleteQuery: [Function: deleteQuery],
showIndexesQuery: [Function: showIndexesQuery],
showConstraintsQuery: [Function: showConstraintsQuery],
removeIndexQuery: [Function: removeIndexQuery],
attributeToSQL: [Function: attributeToSQL],
attributesToSQL: [Function: attributesToSQL],
quoteIdentifier: [Function: quoteIdentifier],
_checkValidJsonStatement: [Function: _checkValidJsonStatement],
jsonPathExtractionQuery: [Function: jsonPathExtractionQuery],
_getForeignKeysQueryFields: [Function: _getForeignKeysQueryFields],
getForeignKeysQuery: [Function: getForeignKeysQuery],
getForeignKeyQuery: [Function: getForeignKeyQuery],
dropForeignKeyQuery: [Function: dropForeignKeyQuery],
_templateSettings: [Object],
options: [Object],
extractTableDetails: [Function: extractTableDetails],
addSchema: [Function: addSchema],
dropSchema: [Function: dropSchema],
describeTableQuery: [Function: describeTableQuery],
dropTableQuery: [Function: dropTableQuery],
renameTableQuery: [Function: renameTableQuery],
insertQuery: [Function: insertQuery],
bulkInsertQuery: [Function: bulkInsertQuery],
updateQuery: [Function: updateQuery],
arithmeticQuery: [Function: arithmeticQuery],
nameIndexes: [Function: nameIndexes],
addIndexQuery: [Function: addIndexQuery],
addConstraintQuery: [Function: addConstraintQuery],
getConstraintSnippet: [Function: getConstraintSnippet],
removeConstraintQuery: [Function: removeConstraintQuery],
quoteTable: [Function: quoteTable],
quote: [Function: quote],
quoteIdentifiers: [Function: quoteIdentifiers],
escape: [Function: escape],
selectQuery: [Function: selectQuery],
escapeAttributes: [Function: escapeAttributes],
generateInclude: [Function: generateInclude],
generateJoin: [Function: generateJoin],
generateThroughJoin: [Function: generateThroughJoin],
_generateSubQueryFilter: [Function: _generateSubQueryFilter],
_getRequiredClosure: [Function: _getRequiredClosure],
getQueryOrders: [Function: getQueryOrders],
selectFromTableFragment: [Function: selectFromTableFragment],
setAutocommitQuery: [Function: setAutocommitQuery],
setIsolationLevelQuery: [Function: setIsolationLevelQuery],
generateTransactionId: [Function: generateTransactionId],
startTransactionQuery: [Function: startTransactionQuery],
deferConstraintsQuery: [Function: deferConstraintsQuery],
setConstraintQuery: [Function: setConstraintQuery],
setDeferredQuery: [Function: setDeferredQuery],
setImmediateQuery: [Function: setImmediateQuery],
commitTransactionQuery: [Function: commitTransactionQuery],
rollbackTransactionQuery: [Function: rollbackTransactionQuery],
addLimitAndOffset: [Function: addLimitAndOffset],
whereQuery: [Function: whereQuery],
whereItemsQuery: [Function: whereItemsQuery],
OperatorsAliasMap: false,
setOperatorsAliases: [Function: setOperatorsAliases],
whereItemQuery: [Function: whereItemQuery],
_findField: [Function: _findField],
_replaceAliases: [Function: _replaceAliases],
_whereGroupBind: [Function: _whereGroupBind],
_whereBind: [Function: _whereBind],
_whereJSON: [Function: _whereJSON],
_traverseJSON: [Function: _traverseJSON],
_castKey: [Function: _castKey],
_getJsonCast: [Function: _getJsonCast],
_joinKeyValue: [Function: _joinKeyValue],
_getSafeKey: [Function: _getSafeKey],
_prefixKey: [Function: _prefixKey],
_whereParseSingleValueObject: [Function: _whereParseSingleValueObject],
getWhereConditions: [Function: getWhereConditions],
parseConditionObject: [Function: parseConditionObject],
isIdentifierQuoted: [Function: isIdentifierQuoted],
booleanValue: [Function: booleanValue],
_dialect: [Circular],
sequelize: [Circular],
typeValidation: undefined } },
queryInterface:
QueryInterface {
sequelize: [Circular],
QueryGenerator:
{ dialect: 'mysql',
OperatorMap: [Object],
createSchema: [Function: createSchema],
showSchemasQuery: [Function: showSchemasQuery],
versionQuery: [Function: versionQuery],
createTableQuery: [Function: createTableQuery],
showTablesQuery: [Function: showTablesQuery],
addColumnQuery: [Function: addColumnQuery],
removeColumnQuery: [Function: removeColumnQuery],
changeColumnQuery: [Function: changeColumnQuery],
renameColumnQuery: [Function: renameColumnQuery],
handleSequelizeMethod: [Function: handleSequelizeMethod],
_toJSONValue: [Function: _toJSONValue],
upsertQuery: [Function: upsertQuery],
deleteQuery: [Function: deleteQuery],
showIndexesQuery: [Function: showIndexesQuery],
showConstraintsQuery: [Function: showConstraintsQuery],
removeIndexQuery: [Function: removeIndexQuery],
attributeToSQL: [Function: attributeToSQL],
attributesToSQL: [Function: attributesToSQL],
quoteIdentifier: [Function: quoteIdentifier],
_checkValidJsonStatement: [Function: _checkValidJsonStatement],
jsonPathExtractionQuery: [Function: jsonPathExtractionQuery],
_getForeignKeysQueryFields: [Function: _getForeignKeysQueryFields],
getForeignKeysQuery: [Function: getForeignKeysQuery],
getForeignKeyQuery: [Function: getForeignKeyQuery],
dropForeignKeyQuery: [Function: dropForeignKeyQuery],
_templateSettings: [Object],
options: [Object],
extractTableDetails: [Function: extractTableDetails],
addSchema: [Function: addSchema],
dropSchema: [Function: dropSchema],
describeTableQuery: [Function: describeTableQuery],
dropTableQuery: [Function: dropTableQuery],
renameTableQuery: [Function: renameTableQuery],
insertQuery: [Function: insertQuery],
bulkInsertQuery: [Function: bulkInsertQuery],
updateQuery: [Function: updateQuery],
arithmeticQuery: [Function: arithmeticQuery],
nameIndexes: [Function: nameIndexes],
addIndexQuery: [Function: addIndexQuery],
addConstraintQuery: [Function: addConstraintQuery],
getConstraintSnippet: [Function: getConstraintSnippet],
removeConstraintQuery: [Function: removeConstraintQuery],
quoteTable: [Function: quoteTable],
quote: [Function: quote],
quoteIdentifiers: [Function: quoteIdentifiers],
escape: [Function: escape],
selectQuery: [Function: selectQuery],
escapeAttributes: [Function: escapeAttributes],
generateInclude: [Function: generateInclude],
generateJoin: [Function: generateJoin],
generateThroughJoin: [Function: generateThroughJoin],
_generateSubQueryFilter: [Function: _generateSubQueryFilter],
_getRequiredClosure: [Function: _getRequiredClosure],
getQueryOrders: [Function: getQueryOrders],
selectFromTableFragment: [Function: selectFromTableFragment],
setAutocommitQuery: [Function: setAutocommitQuery],
setIsolationLevelQuery: [Function: setIsolationLevelQuery],
generateTransactionId: [Function: generateTransactionId],
startTransactionQuery: [Function: startTransactionQuery],
deferConstraintsQuery: [Function: deferConstraintsQuery],
setConstraintQuery: [Function: setConstraintQuery],
setDeferredQuery: [Function: setDeferredQuery],
setImmediateQuery: [Function: setImmediateQuery],
commitTransactionQuery: [Function: commitTransactionQuery],
rollbackTransactionQuery: [Function: rollbackTransactionQuery],
addLimitAndOffset: [Function: addLimitAndOffset],
whereQuery: [Function: whereQuery],
whereItemsQuery: [Function: whereItemsQuery],
OperatorsAliasMap: false,
setOperatorsAliases: [Function: setOperatorsAliases],
whereItemQuery: [Function: whereItemQuery],
_findField: [Function: _findField],
_replaceAliases: [Function: _replaceAliases],
_whereGroupBind: [Function: _whereGroupBind],
_whereBind: [Function: _whereBind],
_whereJSON: [Function: _whereJSON],
_traverseJSON: [Function: _traverseJSON],
_castKey: [Function: _castKey],
_getJsonCast: [Function: _getJsonCast],
_joinKeyValue: [Function: _joinKeyValue],
_getSafeKey: [Function: _getSafeKey],
_prefixKey: [Function: _prefixKey],
_whereParseSingleValueObject: [Function: _whereParseSingleValueObject],
getWhereConditions: [Function: getWhereConditions],
parseConditionObject: [Function: parseConditionObject],
isIdentifierQuoted: [Function: isIdentifierQuoted],
booleanValue: [Function: booleanValue],
_dialect: [Object],
sequelize: [Circular],
typeValidation: undefined } },
models: {},
modelManager: ModelManager { models: [], sequelize: [Circular] },
connectionManager:
ConnectionManager {
sequelize: [Circular],
config:
{ database: 'node',
username: 'root',
password: '1234567890',
host: 'localhost',
port: undefined,
pool: [Object],
protocol: 'tcp',
native: false,
ssl: undefined,
replication: false,
dialectModulePath: null,
keepDefaultTimezone: undefined,
dialectOptions: undefined },
dialect:
MysqlDialect {
sequelize: [Circular],
connectionManager: [Circular],
QueryGenerator: [Object] },
versionPromise: null,
dialectName: 'mysql',
pool:
Pool {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
_config: [Object],
_Promise: [Object],
_factory: [Object],
_draining: false,
_started: false,
_waitingClientsQueue: [Object],
_factoryCreateOperations: Set {},
_factoryDestroyOperations: Set {},
_availableObjects: [Object],
_testOnBorrowResources: Set {},
_testOnReturnResources: Set {},
_validationOperations: Set {},
_allObjects: Set {},
_resourceLoans: Map {},
_evictionIterator: [Object],
_evictor: DefaultEvictor {},
_scheduledEviction: null },
lib:
{ createConnection: [Function],
connect: [Function],
Connection: [Function: Connection],
createPool: [Function],
createPoolCluster: [Function],
createQuery: [Function: createQuery],
Pool: [Function: Pool],
createServer: [Function],
PoolConnection: [Object],
escape: [Function: escape],
escapeId: [Function: escapeId],
format: [Function: format],
raw: [Function: raw],
createConnectionPromise: [Getter],
createPoolPromise: [Getter],
createPoolClusterPromise: [Getter],
Types: [Getter],
Charsets: [Getter],
CharsetToEncoding: [Getter],
setMaxParserCache: [Function],
clearParserCache: [Function] } },
importCache: {},
test:
{ _trackRunningQueries: false,
_runningQueries: 0,
trackRunningQueries: [Function: trackRunningQueries],
verifyNoRunningQueries: [Function: verifyNoRunningQueries] } }
model product.js
const Sequelize = require('sequelize');
const sequelize = require('./dbconfig');
const Product = sequelize.define('product', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
title: Sequelize.STRING,
price: {
type: Sequelize.DOUBLE,
allowNull: false
},
imageUrl: {
type: Sequelize.STRING,
allowNull: false
},
description: {
type: Sequelize.STRING,
allowNull: false
}
});
module.exports = Product;
App.js
const express = require('express');
const feedroutes = require('./routes/feed');
const bodyParser = require('body-parser');
const sequelize = require('./dbconfig');
const app = express()
app.use(bodyParser.json());//application/json
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
app.use('/feed',feedroutes);
sequelize.sync().then(reslut => {
console.log(reslut);
app.listen(8080);
})
.catch(error => {
console.log(error);
});
dbconfig.js
const Sequelize = require('sequelize');
const sequelize = new Sequelize('node','root','1234567890', {
operatorsAliases: false ,
dialect: 'mysql',
host:'localhost'
});
module.exports = sequelize;
since your product model is in a separate file you are required to import it using the import method available on sequelize instance as follows
model product.js
module.exports = function(sequelize, Sequelize) {
const Product = sequelize.define('product', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
title: Sequelize.STRING,
price: {
type: Sequelize.DOUBLE,
allowNull: false
},
imageUrl: {
type: Sequelize.STRING,
allowNull: false
},
description: {
type: Sequelize.STRING,
allowNull: false
}
});
module.exports = Product;
};
dbconfig.js
const Sequelize = require('sequelize');
const sequelize = new Sequelize('node','root','1234567890', {
operatorsAliases: false ,
dialect: 'mysql',
host:'localhost'
});
sequelize.import('path/to/product/model');
module.exports = sequelize;
Reference sequelize import
Project Demo
Your route middleware always should be located after sequelize.sync() (not only sequelize.sync() but all configs related to your application)
After route response with res.render() or res.send() etc, next() will not be invoked.
Whereas You can locate your error handling middleware after the route middlewares.
According to the doc for web3: http://web3js.readthedocs.io/en/1.0/web3-eth-accounts.html
I can use:
web3.eth.accounts.privateToAccount("0x78...");
I have this error:
TypeError: 'privateToAccount' is not a function
at <anonymous>:1:1
web3.eth.accounts is defined:
> web3.eth.accounts
["0x78...", "0xf3..."]
My question: why the function 'privateToAccount' is not defined ?
Also the result of web3.eth.accounts are private or public keys ?
Ok, I just ran into the same issue and was able to reproduce this.
After some digging I noticed the linked docs are for version 1.0 which is an unreleased future version and uncompleted milestone.
Check your web3.version:
> web3.version
{ api: '0.18.4',
node: [Getter],
getNode: { [Function: get] request: [Function: bound ] },
network: [Getter],
getNetwork: { [Function: get] request: [Function: bound ] },
ethereum: [Getter],
getEthereum: { [Function: get] request: [Function: bound ] },
whisper: [Getter],
getWhisper: { [Function: get] request: [Function: bound ] } }
You will probably get 0.18.x which does not support any eth.accounts sub-functions:
> web3.eth.accounts
web3.eth.accounts
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
I am hosting an application server with Express (Versions: "body-parser": 1.14.2", "express": "^4.13.3", "parse-http-header": "^1.0.0", "x509": "^0.2.3")
Node v5.4.1 NPM v3.3.12
I have successfully tested the SSL connection between Alexa and my local App server, however, when I parse the Request from Alexa it doesn't match my Intent Schema or the generated Service Request under the Service Simulator - Test.
Code:
const fs = require('fs'); //File System, for loading certifications and keys
var http = require('http');
var https = require('https'); //Https server module
var bodyParser = require('body-parser');
var parseHttpHeader = require('parse-http-header');
/***************** Credentials **********************/
const privateKey = fs.readFileSync('keys/private-key.pem'); //Private Key for validation (server uses only)
const certificate = fs.readFileSync('certs/certificate.pem'); //Certificate, to provide to connecting host.
const options = {
key: privateKey,
cert: certificate
};
/******** Instantiate the Express server *************/
var express = require('express');
var app = express(); //Instantiate express server
//Express configuration
app.set('title', 'mySkillJS');
app.set('json spaces', 2);
//Route all requests from app
app.all('/*', function(request, response){
//Handle request
var bucket = request;
console.log('\n \n \n &&&&&& \n \n \n');
var joptions = {
type: 'application/json'
}
var bodyParsed = app.use(bodyParser.json(joptions));
console.log(bodyParsed);
var headParsed = parseHttpHeader(bucket.headers['content-type'])[0];
console.log(headParsed);
});
//Ceate Server with SSL credentials
var httpsServer = https.createServer(options, app).listen(8000);//createServer(options, fx(req, res))
Intent Schema:
{
"intents": [
{
"intent": "HelloWorldIntent"
},
{
"intent": "AMAZON.HelpIntent"
}
]
}
generated Service Request:
{
"session": {
"sessionId": "SessionId.efb0235c-8201-4877-832e-58671b42c9b5",
"application": {
"applicationId": "amzn1.echo-sdk-ams.app.9eb766d1-f6a6-4ac7-9801-ce1478782b98"
},
"user": {
"userId": "amzn1.echo-sdk-account.AHUTLGA6FMHPERGIUSQTTXG2RLOABOBTGSGN4LXBEWYK2XDLDRXU2"
},
"new": true
},
"request": {
"type": "IntentRequest",
"requestId": "EdwRequestId.734c7e4a-ec2c-4bdf-b2bc-37757796e670",
"timestamp": "2016-01-22T04:10:18Z",
"intent": {
"name": "HelloWorldIntent",
"slots": {}
}
}
}
Request from Alexa handled by my app server:
&&&&&&
{ [Function]
domain: undefined,
_events: { mount: [Function: onmount] },
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
once: [Function: once],
removeListener: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
listenerCount: [Function: listenerCount],
init: [Function: init],
defaultConfiguration: [Function: defaultConfiguration],
lazyrouter: [Function: lazyrouter],
handle: [Function: handle],
use: [Function: use],
route: [Function: route],
engine: [Function: engine],
param: [Function: param],
set: [Function: set],
path: [Function: path],
enabled: [Function: enabled],
disabled: [Function: disabled],
enable: [Function: enable],
disable: [Function: disable],
acl: [Function],
bind: [Function],
checkout: [Function],
connect: [Function],
copy: [Function],
delete: [Function],
get: [Function],
head: [Function],
link: [Function],
lock: [Function],
'm-search': [Function],
merge: [Function],
mkactivity: [Function],
mkcalendar: [Function],
mkcol: [Function],
move: [Function],
notify: [Function],
options: [Function],
patch: [Function],
post: [Function],
propfind: [Function],
proppatch: [Function],
purge: [Function],
put: [Function],
rebind: [Function],
report: [Function],
search: [Function],
subscribe: [Function],
trace: [Function],
unbind: [Function],
unlink: [Function],
unlock: [Function],
unsubscribe: [Function],
all: [Function: all],
del: [Function],
render: [Function: render],
listen: [Function: listen],
request: IncomingMessage { app: [Circular] },
response: ServerResponse { app: [Circular] },
cache: {},
engines: {},
settings:
{ 'x-powered-by': true,
etag: 'weak',
'etag fn': [Function: wetag],
env: 'development',
'query parser': 'extended',
'query parser fn': [Function: parseExtendedQueryString],
'subdomain offset': 2,
'trust proxy': false,
'trust proxy fn': [Function: trustNone],
view: [Function: View],
views: '/home/dev/Alexa/alexa-js-mod/samples/helloWorld/src/views',
'jsonp callback name': 'callback',
title: 'mySkillJS',
'json spaces': 2 },
_eventsCount: 1,
locals:
{ settings:
{ 'x-powered-by': true,
etag: 'weak',
'etag fn': [Function: wetag],
env: 'development',
'query parser': 'extended',
'query parser fn': [Function: parseExtendedQueryString],
'subdomain offset': 2,
'trust proxy': false,
'trust proxy fn': [Function: trustNone],
view: [Function: View],
views: '/home/dev/Alexa/alexa-js-mod/samples/helloWorld/src/views',
'jsonp callback name': 'callback',
title: 'mySkillJS',
'json spaces': 2 } },
mountpath: '/',
_router:
{ [Function: router]
params: {},
_params: [],
caseSensitive: false,
mergeParams: undefined,
strict: false,
stack: [ [Object], [Object], [Object], [Object] ] } }
application/json
I am not sure what I am doing wrong. I thought that Request would hold something similar to either my Intent Schema or the generated Service Request. Why don't I see Intent Schema or my generated Service Request in the JSON Request I receive from Alexa?
So this problem arose because of inexperience with the express module.
I thought bodyParsed would hold a value returned from: app.use(bodyParser.json());
when you use app.use(bodyParser.json());
It actually stores it in the body property of the Request.
So:
app.use(bodyParser.json(joptions));//causes request.body to populate with the JSON data
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded requires multer
app.all('/*', function(request, response){
//Handle request
var bucket = request;
console.log('\n \n \n &&&&&& \n \n \n');
var joptions = {
type: 'application/json'
}
console.log(request.body));
var headParsed = parseHttpHeader(bucket.headers['content-type'])[0];
console.log(headParsed);
});
Not sure if this forces all requests to be parsed as application/json. Maybe moving the bodyparser inside the app.all() will cause it to only parse when using that route?
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)});