I'm trying to make use of the getquery for graphql in react.js. But I can't figure out how to go about doing this. I already succeeded to use the list query.
state = { patients: [] }
async componentDidMount() {
try {
const apiData = await API.graphql(graphqlOperation(listxxxx))
const patie = apiData.data.listxxxx.items
this.setState({ patie })
console.log(patie)
} catch (err) {
console.log('qqqqqqqqqqqqqqqqq ', err)
}
}
How does one go about using the get query? Thanks!
You need an ID to retrieve an item with any get query. getPatient(id:"YOUR ID HERE"){}`
Something like...
query Get_Patient_By_Id{
getPatient(id:"2dbcb870-e302-4ed5-a419-68751597129c"){
id
name
}
}
For React, you'll add in the id to the variables list argument:
const getPatient = await API.graphql(
graphqlOperation(
queries.getPatient,
{id: "2dbcb870-e302-4ed5-a419-68751597129c"}
)
);
console.log(getPatient.data.getPatient);
docs: https://aws-amplify.github.io/docs/js/api#simple-query
Related
Sorry If I'm not explaining this very well. I'm trying to delete from a database using this button press, but whenever I try to delete it will only delete the first item in the database. I'm pretty sure there's something wrong with the ID I'm getting. Can anyone spot any obvious issues I'm missing here?
Button Press:
tasksDOM.addEventListener('click', async (e) => {
const el = e.target
if (el.parentElement.classList.contains('delete-btn')) {
loadingDOM.style.visibility = 'visible'
const id = el.parentElement.dataset.id
try {
await axios.delete(`/tm/v1/tasks/${id}`)
showTasks()
} catch (error) {
console.log(error)
}
}
loadingDOM.style.visibility = 'hidden'
})
Delete:
app.delete("/tm/v1/tasks/:id", async (req, res) => {
try {
const id = req.params.id;
const response = await Task.findOneAndDelete({ id });
res.status(200).json({ msg: 'deleted' });
} catch (error) {
res.status(500).json({ msg: error });
};
});
Two solutions -
1. const response = await Task.findByIdAndDelete(id);
2. const response = await Task.findOneAndDelete({ _id : mongoose.Types.ObjectId(id) });
Don't forget to import mongoose for second method.
Explanation -
In your code findOneAndDelete is taking id as argument which doesn't exist for mongoose so default, its deleting the first entry so you need to use _id here. Second thing is, id param is string type and _id is ObjectId so it will not match. To match this, you need to convert this string value to mongoose ObjectId.
findByIdAndDelete works with string value as well!
I tried to find the solutions over here but unable to get success while using $pull as the array values I have does not contain `mongo_id'.
So the scenario is that , I am trying to delete the specific comment of the particular user which I am passing through query params. M
My mongo data looks like this:
Now I am making API Delete request like this : http://localhost:8000/api/articles/learn-react/delete-comment?q=1 on my localhost .
ANd finally my code looks like this:
import express from "express";
import bodyParser from "body-parser";
import { MongoClient } from "MongoDB";
const withDB = async (operations, res) => {
try {
const client = await MongoClient.connect(
"mongodb://localhost:27017",
{ useNewUrlParser: true },
{ useUnifiedTopology: true }
);
const db = client.db("my-blog");
await operations(db);
client.close();
} catch (error) {
res.status(500).json({ message: "Error connecting to db", error });
}
};
app.delete("/api/articles/:name/delete-comment", (req, res) => {
const articleName = req.params.name;
const commentIndex = req.query.q;
withDB(async(db) => {
try{
const articleInfo = await db.collection('articles').findOne({name:articleName});
let articleAllComment = articleInfo.comments;
console.log("before =",articleAllComment)
const commentToBeDeleted = articleInfo.comments[commentIndex];
//console.log(commentToBeDeleted)
// articleAllComment.update({
// $pull: { 'comments':{username: commentToBeDeleted.username }}
// });
articleAllComment = articleAllComment.filter( (item) => item != commentToBeDeleted );
await articleAllComment.save();
console.log("after - ",articleAllComment);
//yaha per index chahiye per kaise milega pta nhi?
//articleInfo.comments = gives artcle comment
res.status(200).send(articleAllComment);
}
catch(err)
{
res.status(500).send("Error occurred")
}
},res);
});
I have used the filter function but it is not showing any error in terminal but also getting 500 status at postman.
Unable to figure out the error?
I believe you'll find a good answer here:
https://stackoverflow.com/a/4588909/9951599
Something to consider...
You can use MongoDB's built-in projection methods to simplify your code.
https://docs.mongodb.com/manual/reference/operator/projection/positional/#mongodb-projection-proj.-
By assigning a "unique ID" to each of your comments, you can find/modify the comment quickly using an update command instead of pulling out the comment by order in the array. This is more efficient, and much simpler. Plus, multiple read/writes at once won't interfere with this logic during busy times, ensuring that you're always deleting the right comment.
Solution #1: The recommended way, with atomic operators
Here is how you can let MongoDB pull it for you if you give each of your comments an ID.
await db.collection('articles').updateOne({ name:articleName },
{
$pull:{ "comments.id":commentID }
});
// Or
await db.collection('articles').updateOne({ name:articleName, "comments.id":commentID },
{
$unset:{ "comments.$":0 }
});
Solution #2 - Not recommended
Alternatively, you could remove it by index:
// I'm using "3" here staticly, put the index of your comment there instead.
db.collection('articles').updateOne({ name:articleName }, {
$unset : { "comments.3":0 }
})
I do not know why your filter is erroring, but I would recommend bypassing the filter altogether and try to utilize MongoDB's atomic system for you.
I want to get collection data based on UserId field .
getData(){
const data$ = this.fbs.collection(this.trackerData,ref=> ref.where('UserId','==',"WrKDk0XSNjU20FI0EVRvADzvNHz1")).snapshotChanges().subscribe(res=>{
console.log(res);
});
}
if i get data like this i am getting response as :-
but i need response data like :-
You need to transform your stream to get what you want:
getData(userId: string){
return this.fbs.collection(
this.trackerData,
ref=> ref.where('UserId','==',userId)
).snapshotChanges().pipe(
map(action => {
const data = action.payload.data();
const id = action.payload.id;
return { id, ...data };
})
);
}
getData("WrKDk0XSNjU20FI0EVRvADzvNHz1").subscribe(res=> console.log(res));
There unfortunately aren't any good examples in the docs of how to pass a variable into a filter as far as I can tell. Here's an example of a query that works in App Sync:
query listPayments {
listPayments(filter: {residentId: {contains: "some_random_id"}}) {
items {
timestamp
totalAmount
feeAmount
transactionId
paymentTraceId
paymentReferenceId
paymentMethodId
}
}
}
But I have no idea how to pass that into my function which then interacts with the template string:
export const getResidentPayments = async (residentId) => {
console.log('getting payments...')
try {
paymentHistoryResponse = (await API.graphql(
graphqlOperation(listPayments, {
input: {id: residentId}
}),
)).data
console.log('payment history res', paymentHistoryResponse);
paymentHistoryResponse = JSON.parse(paymentHistoryResponse);
return paymentHistoryResponse
} catch (error) {
console.log('got payment history err', error);
throw error;
}
}
const listPayments = ` query listPayments ($residentId: id ) {
listPayments(filter: {residentId: {contains: $residentId}}) {
items {
timestamp
totalAmount
feeAmount
transactionId
paymentTraceId
paymentReferenceId
paymentMethodId
}
}
}
`;
It would be greatly appreciated if somebody could tell me what I'm doing wrong since it's probably a fairly obvious rookie mistake. I'm shocked that graphql doesn't have a documentation example for this, unless I'm mistaken about that as well.
AppSync builds a lot of the functionality for you. What's the Type Def for listPayments?
Did you make a filter input for listPayments that takes a field and a string?
I am creating routers using koa. We have declared two routers as shown below.
app.get('/order/:id', async ctx => {
const { id } = ctx.params;
try {
const data = await order.findOne({
where: { order_id: id }
});
ctx.body = data;
} catch (e) {
ctx.body = e.message;
}
});
app.get('/order/customer', async ctx => {
const { id } = ctx.request.user;
try {
const data = await order.findOne({
where: { customer_id: id }
});
ctx.body = data;
} catch (e) {
ctx.body = e.message;
}
});
The first is a query that selects an order by order_id, and the second is a query that selects the order of the user with an id authenticated by the middleware.
curl http://localhost:3000/order/1
The order_id is 1 when I type in the above.
curl http://localhost:3000/order/customer
However, unlike my intention, when I enter the above, and check the query, the order_id is called customer. Is there any way I can make url simple to make /order/customer available?
If you have any questions I'm missing from the question or if you can help me, please comment or reply.
You're having the issue with order of routes definitions. You should have specific path route first and dynamic route later. Here, dynamic route I meant for /:id:
'/order/customer' // first
'/order/:id' // later