MongoSkin wrong insertion - node.js

I have an array with countries with the following structure:
{
"code": "ZW",
"name": "Zimbabwe",
"zipPattern": "[\\s\\S]*",
"states": [
{
"name": "Bulawayo"
},
{
"name": "Harare"
},
{
"name": "Manicaland"
},
{
"name": "Mashonaland Central"
},
{
"name": "Mashonaland East"
},
{
"name": "Mashonaland West"
},
{
"name": "Masvingo"
},
{
"name": "Matabeleland North"
},
{
"name": "Matabeleland South"
},
{
"name": "Midlands"
}
]
}
I am trying to insert them into MongoDb using MongoSkin with the following code
var countries = require('./mongo/ready/Countries');
db.collection('countries').find().toArray(function (err, result) {
if (result.length === 0) {
for (var i = 0; i < countries.length; i++) {
var obj = countries[i];
var states = obj.states;
db.collection('countries').insert({
name: obj.name,
code: obj.code,
zipPattern: obj.zipPattern
}, function (error, countryResult) {
var id = countryResult[0]._id;
for (var j = 0; j < states.length; j++) {
var state = states[j];
db.collection('states').insert({
countryId: id,
name: state.name
}, function (stateError, stateResult) {
if (stateError) console.log(stateError);
console.log(stateResult);
});
}
});
}
}
});
but the code inserts the states of the last country in the array (Zimbabwe) for each country in the array instead of the correct states. How can I fix it?

Generally we don't use async query(insert) between sync loop(simple for loop). Its give us abnoramal results. Node provides async loop to overcome this.
First of all require async module for this.
var async = require('async');
Now you can use following code for insertion of countries and their respective states
async.each(countries, function(obj, callback) {
var states = obj.states;
db.collection('countries').insert({
name: obj.name,
code: obj.code,
zipPattern: obj.zipPattern
}, function(error, countryResult) {
if (error) {
callback(error);
} else {
var id = countryResult[0]._id;
async.each(states, function(state, callback) {
db.collection('states').insert({
countryId: id,
name: state.name
}, function(stateError, stateResult) {
if (stateError) {
callback(stateError);
} else {
callback();
}
});
});
callback();
}
}); }, function(err) {
if (err) {
// handle error here
} else {
// do stuff on completion of insertion
} });
Thanks

Related

Node - build a tree recursively with API data

I need to build a tree like structure using data from an API.
The structure i start with is as follows:
{
"type": "group",
"id": 1,
"name": "rootGroup",
"members": [],
}
There will always be a root group as the base of the tree.
I have a function named getMembersInGroup(groupId) which is an API call and returns something like:
[
{
"type": "group",
"id": 77,
"name": "IT group",
},
{
"type": "user",
"id": 40,
"name": "John"
}
]
Members can either be of type user or another group. So a user would look like:
{
"type": "user",
"id": 40,
"name": "John"
}
If it's another group it needs to recursively fetch those until there are only users or empty array left in members.
Any group can have users at any level with the tree.
A mock of getMembersInGroup:
const getMembersInGroup = async (groupId) => {
try {
const members = await fetch.callApi('/groups/' + groupId + '/members');
if (members) {
return members;
}
else {
return [];
}
} catch (error) {
return { error };
}
}
The end result should look like this:
{
"type": "group",
"id": 1,
"name": "rootGroup",
"members": [
{
"type": "group",
"id": 88,
"name": "Some group",
"members": [
{
"type": "user",
"id": 231,
"name": "SALLY"
},
{
"type": "user",
"id": 232,
"name": "Henry"
}
]
},
{
"type": "user",
"id": 41,
"name": "Chris"
}
],
}
I need help with the algorithm to create the tree.
Your getMembersInGroup function could look like this:
const getMembersInGroup = async (groupId) => {
const members = (await fetch.callApi(`/groups/${groupId}/members`)) ?? [];
for (const member of members) {
if (member.type == "group") {
member.members = await getMembersInGroup(member.id);
}
}
return members;
}
Call it like this:
async function loadTree() {
return {
type: "group",
id: 1,
name: "rootGroup",
members: await getMembersInGroup(1)
};
}
loadTree().then(result =>
console.log(result);
// Work with the result ...
).catch(error =>
console.log("error: ", error)
);
Demo with a mock implementation of fetch.callApi:
// Mock for fetch.callApi
const fetch = {
mockData: [0,[2,3,4],[5,6,7],[8,9],0,0,0,[10],0,0,[11,12],0,0],
callApi(url) {
return new Promise((resolve, reject) => {
const groupId = +url.split("/")[2];
const children = this.mockData[groupId];
if (!children) return reject("not found: " + groupId);
const result = children.map(id => {
const type = this.mockData[id] ? "group" : "user";
return {type, id, name: type + "_" + id};
});
setTimeout(() => resolve(result), 50);
});
}
}
async function loadTree() {
return {
type: "group",
id: 1,
name: "rootGroup",
members: await getMembersInGroup(1)
};
}
const getMembersInGroup = async (groupId) => {
const members = (await fetch.callApi('/groups/' + groupId + '/members')) ?? [];
for (const member of members) {
if (member.type == "group") {
member.members = await getMembersInGroup(member.id);
}
}
return members;
}
loadTree().then(result =>
console.log(JSON.stringify(result, null, 2))
).catch(error =>
console.log("error: ", error)
);
You can do something like:
const getMembersInGroup = async (groupId) => {
try {
const members = await fetch.callApi('/groups/' + groupId + '/members');
if (members) {
foreach(member in members) {
if (member.type == 'groups') {
member.members = getMembersInGroup(member.groupid)
}
}
return members;
}
else {
return [];
}
} catch (error) {
return { error };
}
}
So you have the recursion only if it's a group type, otherwise the member is returned as is.

How to convert for urlencoded array into json in node js

I am having a form-urlencoded request as follows:
but I have to convert this request in json as follows:
{
"version":4.2,
"auth_token": "xxxxxxxx",
"zcontacts":[
{ "phone": "xxxxx", "name": "xxxx" },
{ "phone": "112", "name": "Distress Number" },
{ "phone": "1800-300-xxxx", "name": "UIDAI" },
{ "phone": "44 xxxxx, "name": "Ab zz" }
]
}
Here below is my code which I am trying:
index(req_data) {
const self = this;
return new Promise((resolve, reject) => {
console.log(typeof req_data)
let req_body = {}
req_body.version = req_data.version;
req_body.auth_token = req_data.auth_token;
let contacts_list = [];
return Promise.each(req_data.zcontacts,(contact, key, length) => {
// Logic starts from here
if(key === 0) {
contacts_list.push({
phone: req_data.zcontacts[key],
name: req_data.zcontacts[(key+1)]
})
} else if(key > 0) {
contacts_list.push({
phone: req_data.zcontacts[(key+3)],
name: req_data.zcontacts[(key+4)]
})
}
}).then(() => {
req_body.zcontacts = contacts_list;
resolve(req_body)
});
Can anyone suggest what should be changed in the code under the loop?
I got it:
return Promise.each(req_data.zcontacts,(contact, key, length) => {
if(key % 2 === 0) {
contacts_list.push({
phone: req_data.zcontacts[key],
name: req_data.zcontacts[(key+1)]
})
}
}).then(() => {
req_body.zcontacts = contacts_list;
resolve(req_body)
});

Alexa Skill Learning: TypeError: Cannot read property 'value' of undefined

I keep getting an error when I try to test my basic skill (I'm trying to learn how to create them).
Here is the error from the log:
2018-11-21T16:10:55.759Z 06a36441-eda8-11e8-a421-f996bf66c592
Unexpected exception 'TypeError: Cannot read property 'value' of
undefined':
TypeError: Cannot read property 'value' of undefined at
Object.getSuggestion (/var/task/index.js:31:54) at emitNone
(events.js:86:13) at AlexaRequestEmitter.emit (events.js:185:7) at
AlexaRequestEmitter.EmitEvent
(/var/task/node_modules/alexa-sdk/lib/alexa.js:216:10) at
AlexaRequestEmitter.ValidateRequest
(/var/task/node_modules/alexa-sdk/lib/alexa.js:181:23) at
AlexaRequestEmitter.HandleLambdaEvent
(/var/task/node_modules/alexa-sdk/lib/alexa.js:126:25) at
AlexaRequestEmitter.value
(/var/task/node_modules/alexa-sdk/lib/alexa.js:100:31)
at exports.handler (/var/task/index.js:52:9)
How can I figure this out?
Here is my code:
var Alexa = require('alexa-sdk');
const APP_ID = 'amzn1.ask.skill.ab07421a-0a92-4c2b-b3bd-998e14286xxx';
const skillData = [
{
city: "Austin",
suggestion: "Austin has some of the most outstanding people."
},
{
city: "San Antonio",
suggestion: "San Antonio has some of the most outstanding people."
},
{
city: "Dallas",
suggestion: "The Dallas metroplex is one of the hottest places."
}
];
var number = 0;
while(number<3){
var handlers = {
'LaunchRequest': function () {
this.emit(':ask', 'Tell me the name of the major city you are closest to'
},
'Unhandled': function () {
this.emit(':ask', 'Try saying a city name like Austin, San Antonio, or Dallas');
},
'getSuggestion': function() {
var city = this.event.request.intent.slots.City.value;
this.emit(':ask', getSuggestion(skillData,'city', city.toUpperCase()).suggestion + '. Give me another city and I\'ll hook you up with the best peeps.');
},
'AMAZON.HelpIntent': function () {
this.emit(':ask', "What can I help you with?", "How can I help?");
},
'AMAZON.CancelIntent': function () {
this.emit(':tell', "Okay!");
},
'AMAZON.StopIntent': function () {
this.emit(':tell', "Goodbye!");
},
};
number = number+1;
}
exports.handler = function(event, context, callback){
var alexa = Alexa.handler(event, context);
alexa.appId = APP_ID;
alexa.registerHandlers(handlers);
alexa.execute();
};
function getSuggestion(arr, propName, cityName) {
for (var i=0; i < arr.length; i++) {
if (arr[i][propName] == cityName) {
return arr[i];
}
}
}
Update
I've made some changes that were suggested below, however, I am still getting an error after the initial response.
"errorMessage": "Cannot read property 'city' of undefined"
Please look at my new code and help me figure this out:
var Alexa = require('alexa-sdk');
const APP_ID = 'amzn1.ask.skill.ab07421a-0a92-4c2b-b3bd-998e14286xxx';
const skillData = [
{
city: 'Austin',
suggestion: "Austin is blahblahblahblahlshflashdfasldfha blah."
},
{
city: 'San Antonio',
suggestion: "San Antonio has blahblahblahblahlshflashdfasldfha blah."
},
{
city: 'Dallas',
suggestion: "The Dallas metroplex is one of the hottest blahblahblahbla blahblahblahblahblahblah."
}
];
var number = 0;
while(number<3){
var handlers = {
'LaunchRequest': function () {
this.emit(':ask', 'Tell me the name of the major city you are closest to!', 'Which major city are you closest to?');
},
'Unhandled': function () {
this.emit(':ask', "Try saying a city name like Austin, San Antonio, or Dallas");
},
'getSuggestion': function() {
var city = this.event.request.intent.slots.city.value;
this.emit(':ask', getSuggestion(skillData,'city', city.toUpperCase()).suggestion + '. Give me another city and I\'ll hook you up with the best peeps.');
},
'AMAZON.HelpIntent': function () {
this.emit(':ask', "What can I help you with?", "How can I help?");
},
'AMAZON.CancelIntent': function () {
this.emit(':tell', "Okay!");
},
'AMAZON.StopIntent': function () {
this.emit(':tell', "Goodbye!");
},
};
number = number+1;
}
exports.handler = function(event, context, callback){
var alexa = Alexa.handler(event, context);
alexa.appId = APP_ID;
alexa.registerHandlers(handlers);
alexa.execute();
};
function getSuggestion(arr, propName, cityName) {
for (var i=0; i < arr.length; i++) {
var prop = arr[i][propName];
prop = prop.toUpperCase();
if (prop == cityName) {
return arr[i];
}
}
}
UPDATE #2
After a lot of trying different things, I've gotten the skill to run with the help of bal simpson!
However, the skill still errors out when the user utters a city name. There must be an error in my Interaction Model, which is below:
{
"interactionModel": {
"languageModel": {
"invocationName": "city picker",
"intents": [
{
"name": "AMAZON.FallbackIntent",
"samples": []
},
{
"name": "AMAZON.CancelIntent",
"samples": []
},
{
"name": "AMAZON.HelpIntent",
"samples": []
},
{
"name": "AMAZON.StopIntent",
"samples": [
"stop"
]
},
{
"name": "AMAZON.NavigateHomeIntent",
"samples": []
},
{
"name": "getSuggestion",
"slots": [],
"samples": [
"san antonio",
"dallas",
"austin"
]
}
],
"types": []
}
}
}
Getting close!!
As a last-ditch effort:
Here is my index.js housed in Lambda. Would anyone mind looking at this?
const LaunchRequestHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === "LaunchRequest";
},
handle(handlerInput) {
console.log("LaunchRequestHandler");
let speechText = 'Lets get you into your new home. Tell me the name of the major city you are closest to!';
let prompt = 'Which major city are you closest to?';
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(prompt)
.getResponse();
}
};
const GetSuggestionIntentHandler = {
canHandle(handlerInput) {
return (
handlerInput.requestEnvelope.request.type === "IntentRequest" &&
handlerInput.requestEnvelope.request.intent.name === "getSuggestion"
);
},
handle(handlerInput) {
let intent = handlerInput.requestEnvelope.request.intent;
let city = intent.slot.city.value;
let suggestion = getSuggestion(skillData,'city', city.toUpperCase()).suggestion;
return handlerInput.responseBuilder
.speak(suggestion)
.reprompt('prompt')
.getResponse();
}
};
const HelpIntentHandler = {
canHandle(handlerInput) {
return (
handlerInput.requestEnvelope.request.type === "IntentRequest" &&
handlerInput.requestEnvelope.request.intent.name === "AMAZON.HelpIntent"
);
},
handle(handlerInput) {
const speechText = "Try saying a city name like Austin, San Antonio, or Dallas";
const promptText = "How can I help?";
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(promptText)
// .withSimpleCard("City Details", speechText)
.getResponse();
}
};
const CancelAndStopIntentHandler = {
canHandle(handlerInput) {
return (
handlerInput.requestEnvelope.request.type === "IntentRequest" &&
(handlerInput.requestEnvelope.request.intent.name ===
"AMAZON.CancelIntent" ||
handlerInput.requestEnvelope.request.intent.name ===
"AMAZON.StopIntent" ||
handlerInput.requestEnvelope.request.intent.name ===
"AMAZON.PauseIntent")
);
},
handle(handlerInput) {
const speechText = `Seeya later!`;
return (
handlerInput.responseBuilder
.speak(speechText)
.withShouldEndSession(true)
.getResponse()
);
}
};
const SessionEndedRequestHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'SessionEndedRequest';
},
handle(handlerInput) {
console.log(`Session ended with reason: ${handlerInput.requestEnvelope.request.reason}`);
return handlerInput.responseBuilder.getResponse();
},
};
const ErrorHandler = {
canHandle() {
return true;
},
handle(handlerInput, error) {
console.log(`Error handled: ${error.message}`);
return handlerInput.responseBuilder
.speak('Sorry, I can\'t understand the command. Try saying a city name like Austin, San Antonio, or Dallas')
.reprompt('Try saying a city name like Austin, San Antonio, or Dallas')
.getResponse();
},
};
const SystemExceptionHandler = {
canHandle(handlerInput) {
return (
handlerInput.requestEnvelope.request.type ===
"System.ExceptionEncountered"
);
},
handle(handlerInput) {
console.log(
`System exception encountered: ${
handlerInput.requestEnvelope.request.reason
}`
);
}
};
const skillBuilder = Alexa.SkillBuilders.custom();
exports.handler = skillBuilder
.addRequestHandlers(
LaunchRequestHandler,
GetSuggestionIntentHandler,
CancelAndStopIntentHandler,
HelpIntentHandler,
SystemExceptionHandler,
SessionEndedRequestHandler
)
.addErrorHandlers(ErrorHandler)
.lambda();
function getSuggestion(arr, propName, cityName) {
for (var i=0; i < arr.length; i++) {
var prop = arr[i][propName];
prop = prop.toUpperCase();
if (prop == cityName) {
return arr[i];
}
}
}
And here is my Interaction Model from the Developer Portal:
{
"interactionModel": {
"languageModel": {
"invocationName": "city picker",
"intents": [
{
"name": "AMAZON.FallbackIntent",
"samples": []
},
{
"name": "AMAZON.CancelIntent",
"samples": []
},
{
"name": "AMAZON.HelpIntent",
"samples": []
},
{
"name": "AMAZON.StopIntent",
"samples": [
"stop"
]
},
{
"name": "AMAZON.NavigateHomeIntent",
"samples": []
},
{
"name": "getSuggestion",
"slots": [
{
"name": "city",
"type": "CITY_NAMES"
}
],
"samples": [
"{city}"
]
}
],
"types": [
{
"name": "CITY_NAMES",
"values": [
{
"name": {
"value": "dallas"
}
},
{
"name": {
"value": "san antonio"
}
},
{
"name": {
"value": "austin"
}
}
]
}
]
}
}
}
ok. alexa-sdk has been deprecated link. To get the new SDK, do this.
1 - Create a new function in Lambda.
2 - Choose AWS Serverless Application Repository.
3 - Choose alexa-skills-kit-nodejs-factskill.
4 - Click on deploy. Once deployed, click on functions and you should see the new function you just created with a name like aws-serverless-repository-alexaskillskitnodejsfact-NR8HPILH8WNI.
5 - Delete the code and replace the code with this.
const Alexa = require('ask-sdk');
const skillData = [
{
city: 'Austin',
suggestion: "Austin is blahblahblahblahlshflashdfasldfha blah."
},
{
city: 'San Antonio',
suggestion: "San Antonio has blahblahblahblahlshflashdfasldfha blah."
},
{
city: 'Dallas',
suggestion: "The Dallas metroplex is one of the hottest blahblahblahbla blahblahblahblahblahblah."
}
];
const LaunchRequestHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === "LaunchRequest";
},
handle(handlerInput) {
console.log("LaunchRequestHandler");
let speechText = 'Tell me the name of the major city you are closest to!';
let prompt = 'Which major city are you closest to?';
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(prompt)
.getResponse();
}
};
const GetSuggestionIntentHandler = {
canHandle(handlerInput) {
return (
handlerInput.requestEnvelope.request.type === "IntentRequest" &&
handlerInput.requestEnvelope.request.intent.name === "getSuggestion"
);
},
handle(handlerInput) {
let intent = handlerInput.requestEnvelope.request.intent;
let city = intent.slots.city.value;
let suggestion = getSuggestion(skillData,'city', city.toUpperCase()).suggestion;
return handlerInput.responseBuilder
.speak(suggestion)
.reprompt('prompt')
.getResponse();
}
};
const HelpIntentHandler = {
canHandle(handlerInput) {
return (
handlerInput.requestEnvelope.request.type === "IntentRequest" &&
handlerInput.requestEnvelope.request.intent.name === "AMAZON.HelpIntent"
);
},
handle(handlerInput) {
const speechText = "Try saying a city name like Austin, San Antonio, or Dallas";
const promptText = "How can I help?";
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(promptText)
// .withSimpleCard("City Details", speechText)
.getResponse();
}
};
const CancelAndStopIntentHandler = {
canHandle(handlerInput) {
return (
handlerInput.requestEnvelope.request.type === "IntentRequest" &&
(handlerInput.requestEnvelope.request.intent.name ===
"AMAZON.CancelIntent" ||
handlerInput.requestEnvelope.request.intent.name ===
"AMAZON.StopIntent" ||
handlerInput.requestEnvelope.request.intent.name ===
"AMAZON.PauseIntent")
);
},
handle(handlerInput) {
const speechText = `Goodbye`;
return (
handlerInput.responseBuilder
.speak(speechText)
.withShouldEndSession(true)
.getResponse()
);
}
};
const SessionEndedRequestHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'SessionEndedRequest';
},
handle(handlerInput) {
console.log(`Session ended with reason: ${handlerInput.requestEnvelope.request.reason}`);
return handlerInput.responseBuilder.getResponse();
},
};
const ErrorHandler = {
canHandle() {
return true;
},
handle(handlerInput, error) {
console.log(`Error handled: ${error.message}`);
return handlerInput.responseBuilder
.speak('Sorry, I can\'t understand the command. Try saying a city name like Austin, San Antonio, or Dallas')
.reprompt('Try saying a city name like Austin, San Antonio, or Dallas')
.getResponse();
},
};
const SystemExceptionHandler = {
canHandle(handlerInput) {
return (
handlerInput.requestEnvelope.request.type ===
"System.ExceptionEncountered"
);
},
handle(handlerInput) {
console.log(
`System exception encountered: ${
handlerInput.requestEnvelope.request.reason
}`
);
}
};
const skillBuilder = Alexa.SkillBuilders.custom();
exports.handler = skillBuilder
.addRequestHandlers(
LaunchRequestHandler,
GetSuggestionIntentHandler,
CancelAndStopIntentHandler,
HelpIntentHandler,
SystemExceptionHandler,
SessionEndedRequestHandler
)
.addErrorHandlers(ErrorHandler)
.lambda();
function getSuggestion(arr, propName, cityName) {
for (var i=0; i < arr.length; i++) {
var prop = arr[i][propName];
prop = prop.toUpperCase();
if (prop == cityName) {
return arr[i];
}
}
}
6 - Go to developer.amazon.com and change your Alexa Skill endpoint to the new lambda ARN.
To add a slot type:
Specify slot in your sample phrases like this:
Change your slot name to city:
So instead of musicStations it will be city. Make sure you have entered the three values in your slot values like this:
Add your custom slot values to CITY_NAMES:
If you have done it right, your interaction model should be something like this:
"name": "getSuggestion",
"slots": [
{
"name": "city",
"type": "CITY_NAMES"
}
],
"samples": [
"city name is {city}",
"{city}"
]
Testing Lambda code
In the drop down menu, choose 'configure test events'.
Create new test event with JSON from your developer test portal which should look like this.
{
"version": "1.0",
"session": {
"new": true,
"sessionId": "amzn1.echo-api.session.XXXXXX",
"application": {
"applicationId": "amzn1.ask.skill.XXXXXX"
},
"user": {
"userId": "amzn1.ask.account.XXXXXX"
}
},
"context": {
"AudioPlayer": {
"playerActivity": "IDLE"
},
"System": {
"application": {
"applicationId": "amzn1.ask.skill.XXXXXX"
},
"user": {
"userId": "amzn1.ask.account.XXXXXX"
},
"device": {
"deviceId": "amzn1.ask.device.XXXXXX",
"supportedInterfaces": {
"AudioPlayer": {}
}
},
"apiEndpoint": "https://api.eu.amazonalexa.com",
"apiAccessToken": "ACCESS_TOKEN"
},
},
"request": {
"type": "IntentRequest",
"requestId": "amzn1.echo-api.request.XXXX",
"timestamp": "2018-12-03T20:28:29Z",
"locale": "en-IN",
"intent": {
"name": "PlayRadioIntent",
"confirmationStatus": "NONE",
"slots": {
"musicStation": {
"name": "musicStation",
"value": "classic rock",
"resolutions": {
"resolutionsPerAuthority": [
{
"authority": "amzn1.er-authority.XXXX.RadioStations",
"status": {
"code": "ER_SUCCESS_MATCH"
},
"values": [
{
"value": {
"name": "Classic Rock",
"id": "b8a5bd97a8a02691f9f81dcfb12184dd"
}
}
]
}
]
},
"confirmationStatus": "NONE",
"source": "USER"
}
}
}
}
Click on test button
Check Logs
Does the test result look like this? To see the logs, click on logs. It might have additional error details.

How to call Web3js function from Nodejs file

I have the following working web3js code, Calling App.createContract() on button click works well on a webpage, however I want to call App.createContract() or similar from another Nodejs controller. Infact what I am thinking of is making an API in Node which could call the web3js function and returns a JSON result back to the caller. Can you please help me how to import my web3js file and call the function from Node Controller? Thanks
import "../stylesheets/app.css";
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract';
import { default as CryptoJS} from 'crypto-js';
var accounts;
var account;
var shLogABI;
var shLogContract;
var shLogCode;
var shLogSource;
window.App = {
start: function() {
var self = this;
web3.eth.getAccounts(function(err, accs) {
if (err != null) {
alert("There was an error fetching your accounts.");
return;
}
if (accs.length == 0) {
alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
return;
}
accounts = accs;
console.log(accounts);
account = accounts[0];
web3.eth.defaultAccount= account;
shLogSource= "pragma solidity ^0.4.6; contract SHLog { struct LogData{ string FileName; uint UploadTimeStamp; string AttestationDate; } mapping(uint => LogData) Trail; uint8 TrailCount=0; function AddNewLog(string FileName, uint UploadTimeStamp, string AttestationDate) { LogData memory newLog; newLog.FileName = FileName; newLog.UploadTimeStamp= UploadTimeStamp; newLog.AttestationDate= AttestationDate; Trail[TrailCount] = newLog; TrailCount++; } function GetTrailCount() returns(uint8){ return TrailCount; } function GetLog(uint8 TrailNo) returns (string,uint,string) { return (Trail[TrailNo].FileName, Trail[TrailNo].UploadTimeStamp, Trail[TrailNo].AttestationDate); } }";
web3.eth.compile.solidity(shLogSource, function(error, shLogCompiled){
shLogABI = JSON.parse(' [ { "constant": false, "inputs": [ { "name": "TrailNo", "type": "uint8" } ], "name": "GetLog", "outputs": [ { "name": "", "type": "string" }, { "name": "", "type": "uint256" }, { "name": "", "type": "string" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "FileName", "type": "string" }, { "name": "UploadTimeStamp", "type": "uint256" }, { "name": "AttestationDate", "type": "string" } ], "name": "AddNewLog", "outputs": [], "payable": false, "type": "function" }, { "constant": false, "inputs": [], "name": "GetTrailCount", "outputs": [ { "name": "", "type": "uint8" } ], "payable": false, "type": "function" } ]');
shLogContract = web3.eth.contract(shLogABI);
});
});
},
createContract: function()
{
shLogContract.new("", {from:account, gas: 3000000}, function (error, deployedContract){
if(deployedContract.address)
{
document.getElementById("contractAddress").value=deployedContract.address;
document.getElementById("fileName").value = '';
document.getElementById("uploadTimeStamp").value = '';
document.getElementById("attestationDate").value = '';
}
})
},
addNewLog: function()
{
var contractAddress = document.getElementById("contractAddress").value;
var deployedshLog = shLogContract.at(contractAddress);
var fileName = document.getElementById("fileName").value;
var uploadTimeStamp = document.getElementById("uploadTimeStamp").value;
var attestationDate = document.getElementById("attestationDate").value;
deployedshLog.AddNewLog(fileName, uploadTimeStamp, attestationDate, function(error){
console.log(error);
})
},
getLog: function()
{
try{
var contractAddress = document.getElementById("contractAddress").value;
var deployedshLog = shLogContract.at(contractAddress);
deployedshLog.GetTrailCount.call(function (error, trailCount){
deployedshLog.GetLog.call(trailCount-1, function(error, returnValues){
document.getElementById("fileName").value= returnValues[0];
document.getElementById("uploadTimeStamp").value = returnValues[1];
document.getElementById("attestationDate").value=returnValues[2];
})
})
}
catch (error) {
document.getElementById("fileName").value= error.message;
document.getElementById("uploadTimeStamp").value = error.message;
document.getElementById("attestationDate").value= error.message;
}
}
};
window.addEventListener('load', function() {
if (typeof web3 !== 'undefined') {
console.warn("Using web3 detected from external source. If using MetaMask, see the following link. Feel free to delete this warning. :) http://truffleframework.com/tutorials/truffle-and-metamask")
window.web3 = new Web3(web3.currentProvider);
} else {
console.warn("No web3 detected. Falling back to http://localhost:8545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask");
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
App.start();
});
Simple example for web3js 1.0.0.beta*
1) Add web3js to your package.json on a server side:
"web3": "^1.0.0-beta.27"
2) Require and init web3 with some provider:
const Web3 = require('web3');
const web3SocketProvider = new Web3.providers.WebsocketProvider('ws://0.0.0.0:8546');
const web3Obj = new Web3(web3Provider);
Now you can use your web3 object as usual:
async function getAccounts() {
let accounts = await web3Obj.eth.getAccounts();
}

Cannot assign to read only property '_id'

get Error Cannot assign to read only property '_id' when insert data in mongodb using node js
Cannot assign to read only property '_id' of
{"Diagnosis":"vvvvv",
"Treatment":[{
"name":"treatment1",
"SubTreatment":[{
"name":"subtreatment1",
"SubTreatment2" : [{
"name":"subtreatmentexp1",
"$$hashKey":"object:27","Name":"vvvvv"
}],
"$$hashKey":"object:22","Name":"vvvvv"
}],
"$$hashKey":"object:12",
"Name":"vvvvv"
}
]}
please help me to solve this error
my code is
app.post('/post', function (req, res) {
var diagnosis;
var obj = req.headers['data'];
var temp = JSON.parse(obj)
console.log("Received body data:");
console.log(obj);
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
insertDocument(temp, db, function () {
db.close();
});
});
var insertDocument = function (obj, db, callback) {
try {
console.log(obj);
db.collection('diagnosis').remove();
db.collection('diagnosis').insertOne(obj, function (err, result) {
assert.equal(err, null);
console.log("Inserted a document into the Diagnosis collection.");
callback();
});
res.send("Inserted a document into the Diagnosis collection.");
} catch (err) {
console.log(err);
}
};
})
my function to call API is
$scope.post = function () {
var diagnosis = $scope.Treatments;
var httpRequest = $http({
method: 'POST',
url: '/post',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'data': JSON.stringify($scope.Treatments)
},
}).success(function (data, status) {
});
};
Treatments array....
$scope.Treatments =
{
Diagnosis: '',
Treatment: [
{
name: 'treatment1',
SubTreatment: [
{
name: 'subtreatment1',
SubTreatment2: [{ name: 'subtreatmentexp1' }]
}
],
}
]
};
Generated JSON to insert data is
{
"Diagnosis": "sss",
"Treatment": [
{
"name": "treatment1",
"SubTreatment": [
{
"name": "subtreatment1",
"SubTreatment2": [
{
"name": "subtreatmentexp1",
"$$hashKey": "object:27",
"Name": "sss"
}
],
"$$hashKey": "object:22",
"Name": "sss"
}
],
"$$hashKey": "object:12",
"Name": "sss"
}
]
}

Resources