Neo4j javascript - Session.run() - how to run multiple query in session - javascript

I am using neo4j javascript driver. I am able to run a single query. But I can't able to create multiple nodes with properties. Can anyone tell me how to do?
session
.run('CREATE (fit1:fitproto {title:"Relaince Industries",name:"Rajni",country:"India",email:"rajni#gmail.com"}),(fit2:fitproto {title:"State Bank of India",name:"Rajni",country:"India",email:"rajni#gmail.com"}) RETURN(fitproto)')
.subscribe({
onNext: function (record) {
const node = record.get(1);
console.log(node);
record.forEach(function (res) {
console.log(res.Node);
});
res.send(record.get(0));
},
onCompleted: function () {
session.close();
},
onError: function (error) {
console.log(error);
}
});

You need to pass an array of properties for new nodes through parameters. Then UNWIND it, create a node and SET properties:
session
.run(`
UNWIND $propsArray as props
CREATE (fit:fitproto) SET fit = props
RETURN fit
`, {
propsArray: [{
title: "Relaince Industries",
name: "Rajni",
country: "India",
email: "rajni#gmail.com"
},
{
title: "State Bank of India",
name: "Rajni",
country: "India",
email: "rajni#gmail.com"
}
]
})
.subscribe({
onNext: function(record) {
console.log(record.get('fit'));
},
onCompleted: function() {
session.close();
},
onError: function(error) {
console.log(error);
}
});

Related

Cannot read property 'affected_rows' of undefined when trying to run an Hasura mutation

I'm using apollo within my vue.js application, I'm currently trying to remove an object by running a mutation, here is the code :
this.$apollo.mutate({
mutation: require("../graphql/deleteTag.gql"),
variables: {
id: idToDelete,
},
update: (store, { data: { delete_tags } }) => {
if (delete_tags.affected_rows) {
const data = store.readQuery({
query: require("../graphql/fetchDevices.gql"),
});
data.device_id_to_tag_id = data.device_id_to_tag_id.filter((x) => {
return x.id != tag.device_id_to_tag_id.id;
});
store.writeQuery({
query: require("../graphql/fetchDevices.gql"),
data,
});
}
},
});
And my deleteTag.gql file :
mutation delete_tags($id: Int!){
delete_extras_taggeditem(where: { id: { _eq: $id } }) {
affected_rows
}
}
But when I run this the following error appears :
I don't really know what's going on because I followed the Hasura vue.js documentation...
Thanks in advance for your help !
You can specify the name of the returned key in graphql if you want your result data to be called just delete_extras instead of delete_extras_taggeditem:
mutation delete_tags($id: Int!){
delete_extras: delete_extras_taggeditem(where: { id: { _eq: $id } }) {
affected_rows
}
}
but right now, you query do not return you a
I believe you are missing optimisticResponse parameter in mutate. the "update" function takes 2 passes - first with data from optimisticResponse, and then the data from the actual mutation response.
e.g. something like...
this.$apollo.mutate({
mutation: require("../graphql/deleteTag.gql"),
variables: {
id: idToDelete,
},
optimisticResponse: {
delete_extras_taggeditem: {
__typename: 'extras_taggeditem',
id: -1,
affected_rows
}
},
update: (store, { data: { delete_extras_taggeditem } }) => {
if (delete_extras_taggeditem.affected_rows) {
const data = store.readQuery({
query: require("../graphql/fetchDevices.gql"),
});
data.device_id_to_tag_id = data.device_id_to_tag_id.filter((x) => {
return x.id != tag.device_id_to_tag_id.id;
});
store.writeQuery({
query: require("../graphql/fetchDevices.gql"),
data,
});
}
},
});
https://apollo.vuejs.org/guide/apollo/mutations.html#server-side-example
Also, generally speaking I would always return id in your responses back for any level of resource. Apollo relies on __typename + id to maintain and manipulate its cache.

Stripe : Error: Received unknown parameter: bank_account[bank_name]

I have been trying to add a bank_name to my Stripe Connect user's external account, but I keep getting an error as if I am misreading the documentation on the function.
Error: Received unknown parameter: bank_account[bank_name]
The documentation shows that I should be able to access the bank_name from the bank_account object, but my error is narrowed down to it being null. My console.log(newValue.externalAccount.bankName) returns the bankName as expected that was entered, so it isn't null going in. Any idea why I am getting this error?
Firebase Function:
exports.createStripeAccount = functions.firestore
.document("users/{userId}")
.onUpdate(async (change, context) => {
const newValue = change.after.data();
const previousValue = change.before.data();
if (newValue.state === "technician" && previousValue.state === "client") {
try {
const account_add_response = await stripe.accounts.create(
{
type: "custom",
country: "US",
requested_capabilities: ["platform_payments"],
email: newValue.email,
tos_acceptance: newValue.stripeTosAcceptance,
business_type: "individual",
business_profile: {
url: newValue.socialLinks.linkedin
},
individual: {
first_name: newValue.firstName,
last_name: newValue.lastName,
gender: newValue.gender,
email: newValue.email,
phone: newValue.phone,
address: {
line1: newValue.address.line1,
line2: newValue.address.line2,
city: newValue.address.city,
state: newValue.address.state,
postal_code: newValue.address.zip,
country: newValue.address.country
},
ssn_last_4: newValue.technician.ssnLast4,
dob: {
day: newValue.dob.day,
month: newValue.dob.month,
year: newValue.dob.year
}
}
},
async function(error, account) {
if (error) {
return console.error(error);
} else {
console.log(
"Writing account.id " + account.id + " to user DB..."
);
console.log("newValue.externalAccount.bankName: " + newValue.externalAccount.bankName)
const bank_add_response = await stripe.accounts.createExternalAccount(
account.id,
{
external_account: {
object: "bank_account",
country: "US",
currency: "USD",
account_holder_name:
newValue.externalAccount.accountHolderName, // Have user input manually, might be different than user's name
account_holder_type: "individual",
bank_name: newValue.externalAccount.bankName,
routing_number: newValue.externalAccount.routingNumber,
account_number: newValue.externalAccount.accountNumber
}
},
function(error, bank_account) {
if (error) {
return console.error(error);
} else {
console.log(
"Writing bank_account.id " +
bank_account.id +
" to user DB..."
);
return admin
.firestore()
.collection("users")
.doc(context.params.userId)
.set(
{
connectId: account.id,
externalAccount: {
bankAccountId: bank_account.id,
bankName: bank_account.bank_name,
last4: bank_account.last4,
}
},
{ merge: true }
);
}
}
);
}
}
);
} catch (error) {
console.log(error);
await change.ref.set(
{ error: userFacingMessage(error) },
{ merge: true }
);
return reportError(error, { user: context.params.userId });
}
}
});
Looks like I misunderstood the purpose of the bank_name field. I thought it was for a custom name the user defines about their bank account, like "Doug's Chase Checkings", but it seems that it's auto generated by Stripe and read only.

Determining pr eliminating empty key:value from an object for multiple filtering purposes

My app has a feature where users can filter results based on "blood group" and "city", and areas. Results will be retrieved from DB using Axios for Vuejs through "URL" query strings. Example url is: http://example.com/api/results?blood=a+&city=london
It should work in a way that when a user select just blood group from select menu: the url would exclude the city parameter. But from my current code, I can't get it stripped of, as a result, the database query returns no results on the basis that cityreturns null value.
Here's what I have in my Vue component:
<script>
export default {
props: ['user'],
data() {
return {
auth_user: this.user,
results: {},
blood_groups: "",
cities: "",
districts: "",
areas: "",
donorUrl: "/api/donors",
requestedBlood: "",
requestedCity: "",
requestedDist: "",
requestedArea: "",
params: {}
};
},
created() {
this.fetchDonors();
this.fetchCities();
},
methods: {
fetchDonors() {
let url = "/api/donors";
axios.get(url).then(response => {
this.results = response.data.data;
this.blood_groups = [...new Set(response.data.data.map(x=> x.blood_group))];
});
},
fetchCities() {
let url = "/api/location_type/cities";
axios.get(url).then(response => {
this.cities = response.data.cities
})
},
selected_blood_group(event) {
this.requestedBlood = event.target.value;
this.get();
},
get_city(event) {
this.requestedCity = event.target.value;
this.get();
},
get() {
let request = {
params: {
blood: this.requestedBlood,
city: this.requestedCity,
dist: this.requestedDist,
area: this.requestedArea
}
}
axios.get('/api/donors', request).then(response => {
this.results = response.data.data
})
}
},
};
</script>
My query is how can I remove or check if any of the following properties contains empty value, so that I do not include them in axios params?
let request = {
params: {
blood: this.requestedBlood,
city: this.requestedCity,
dist: this.requestedDist,
area: this.requestedArea
}
}
You can try below code.
Create a new object(called testParams) and add that object in params.suppose requestedCity is selected(not only but any variable is selected ). Then you can do like below.
if(requestedCity.length!=0)
{
testParams["city"]=requestedCity; // OTHERWISE DON'T ADD IN testParams object
}
Finally while making request through axios add testParams in params object like below.
axios.get('/yourUrl/',{
params:{
testParams //here vue will automatically sets 'testParams':testParams
}
})
I got it working with the following approach:
let request = {
blood: this.requestedBlood,
city: this.requestedCity,
dist: this.requestedDist,
area: this.requestedArea
}
for(let k in request)
if(!request[k]) delete request[k];
axios.get('/api/donors', {
params: request
}).then(response => {
this.results = response.data.data
})

Mongodb - Update property per object in array of object, Insert if doesn't exists

I wish to update a property per object in array of objects, but if some of the objects doesn't exists, insert the object instead.
Currently I used "upsert", which creates a new document when no document matches the query, unfortunately it is replacing a single item with my entire list.
Worth to mention that I am using mongoist to perform an async requests.
My code:
this.tokenArray = [
{ token: "654364543" },
{ token: "765478656" },
{ token: "876584432" },
{ token: "125452346" },
{ token: "874698557" },
{ token: "654364543" }
]
database.upsertDatebaseItem(this.tokenArray.map(x => { return x.token }), { valid : true }, 'Tokens');
async upsertDatebaseItem(itemKey, itemValue, collectionName) {
try {
await this.database[collectionName].update({ token : { $in: itemKey}}, { $set: itemValue }, {upsert : true} , {multi : true});
} catch (error) {
console.log(`An error occurred while attempting to update ${itemType} to the database: ${error}`);
return false;
}
}
Found the way to do it:
const bulkUpdate = this.tokenArray.map((x) => {
return {
"updateOne": {
"filter": { "token": x.token },
"update": { "$set": { "valid": true } },
"upsert": true
}
};
});
and:
this.database[collectionName].bulkWrite(bulkUpdate);
To upsert with mongoist, use the following:
var bulk = db.collection.initializeOrderedBulkOp()
for(var doc of docs) bulk.find( { _id: doc._id } ).upsert().updateOne(doc); // or use replaceOne()
await bulk.execute();
Converted to your case that would be
var bulk = db.collectionName.initializeOrderedBulkOp()
for(var tokenItem of tokenArray) bulk.find( { token : tokenItem.token } ).upsert().updateOne(tokenItem); // or use replaceOne()
await bulk.execute();

How should I format this mock JS data so I can use it after a get request

I have an input field that collects an ID and should use that ID to find the corresponding entry. Below is what I currently have and at the bottom is what I would like to have.
I can get the contents of the file, but I can't do anything with it.
What I currently have:
// mock-data.js
{
id: "239491",
name: "Big Bird",
real: false,
type: "Animal"
}
And in my Vue file I'm using axios for my GET call
// search-file.Vue
axios.get('static/mock-data.js')
.then((response) => {
console.log(response.data)
})
.catch((error) => {
console.error(error)
})
This logs out what appears to be a giant string, because there's no syntax highlighting in the console.
What I would like to have is something like:
{
entries: [
"239491": {
id: "239491",
name: "Big Bird",
real: false,
type: "Animal"
},
"983502": {
id: "983502",
name: "Frodo",
real: false,
type: "Hobbit"
},
...
...
]
}
And my Vue code would ideally be something like:
axios.get('static/mock-data/entries/' + userInput)
.then((response) => {
console.log(response.data)
})
.catch((error) => {
console.error(error)
})
I know this isn't the proper syntax, but I can't find a solution
if you are trying to create a data for test purpose or none blocking front end development, why don't you call it directly? What I would do is f
function mockDataService() {
var mockData = {
entries: [
"239491": {
id: "239491",
name: "Big Bird",
real: false,
type: "Animal"
},
"983502": {
id: "983502",
name: "Frodo",
real: false,
type: "Hobbit"
}
]
};
return {
getMockDataById: function(id) {
//return mock data by id
}
}
}
//you can mock out axios or just create a fake promise.
function callMockData(userInput) {
return {
then: function(success, failure) {
success(mockDataService.getMockDataById(userInput))
}
}
}

Categories