axios post request to MongoDB Atlas error 11000 - reactjs

I am trying to send some data to MongoDB Atlas from a React frontend. I tested the backend (an Express server) with Postman. The routes and endpoints are working as expected, and I can create todos and see them in MongoDB-Atlas.
// createTodo.js
onSubmit(e) {
e.preventDefault()
const todo = {
todoTitle: this.state.todoTitle,
todoBody: this.state.todoBody,
}
console.log(todo)
axios.post('http://localhost:5000/api/todos', todo).then((res) => console.log(res.data))
this.setState({
todoTitle: '',
todoBody: '',
})
}
the (res.data) that I am console.logging gives me an object with a MongoError 11000 code.
Object { driver: true, name: "MongoError", index: 0, code: 11000, keyPattern: {…}, keyValue: {…} }
CreateTodo.js:40
Any one have experience with this type of error? Are there any online resources or guides to help resolve this one? Thank you.

I got this error one time when i defined a collection with a particular name and later on changed the name, hence i believe that mongoDB expected to receive a data attributed to that particular name but didn't and got that error. However, i managed to fix it after dropping the collection and run again.

Related

AxiosError when integrating Stripe with Next.js

I am relatively new to Next.js, and I though I have been encountering some bugs and issues here and there, I have been able to overcome most of them. The latest one I have not been able to figure out, so let's see if somebody else knows what's going on.
I am creating an e-commerce platform on Next.js, Redux and Axios. For the moment I am using fake data to populate the products. When creating a checkout session, the data of the items in the cart is pushed (I can console.log() and I see the items in the terminal. However, the mapping of the checkout session to Stripe is not working. The error I get is an AxiosError: Request failed with status code 500
Error message screenshot
I am trying to add the item data dynamically to the checkout session as follows:
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
export default async (req, res) => {
const { items, email } = req.body;
const transformedItems = items.map((item) => ({
description: item.description,
// if quantities are bundled, this needs to change.
quantity: 1,
price_data: {
currency: 'usd',
unit_amount: item.price * 100,
product_data: {
name: item.title,
images: [item.image],
},
},
}));
const session = await stripe.checkout.sessions.create({
line_items: transformedItems,
mode: 'payment',
success_url: `${process.env.HOST}/success`,
cancel_url: `${process.env.HOST}/checkout`,
metadata: {
email,
images: JSON.stringify(items.map((item) => item.image)),
},
});
res.status(200).json({ id: session.id });
};
I have also tried copying the exact code from the Stripe documentation and implementing the changes, but this hasn't changed anything either.
I know, Stripe has made some changes to their API, and that for instance you can't specify anymore with statements like
payment_method_types: ["card"],
anymore. So I took it out.
I have not included any code from the checkout piece, as this seems to be working (as stated, it console.logs() just fine. I can provide this as well though, if someone thinks the issue might be there.
Thanks in advance.
Nela.
Thanks to Code-Apprentice and maiorano84 whose hints in the comments:
A status code 500 means there is an error on the backend. If the server is under your control, then you need to look at the server logs to see what the problem is. The server logs will have a stack trace that shows you where the problem occurs. If you need help understanding the stacktrace, you will need to include it in your question. – Code-Apprentice 22 hours ago
Is this a server-side or client-side AJAX request? If it's the latter, check your network tab to see the full output of your failed request (marked in red in Chrome Devtools). You should be able to get more information about the failed request there. If it's failing on the Stripe side, the Response Headers and Body should have more information there to help you debug. If it's failing on your own success and checkout callbacks, your server logs might have additional information that can help you. – maiorano84 22 hours ago
led me to the answer. I checked my console, and the error that was given was from Stripe. It read as follows:
StripeInvalidRequestError: You cannot use line_items.amount, line_items.currency, line_items.name, line_items.description, or line_items.images in this API version. Please use line_items.price or line_items.price_data.
So I moved the item.description I had outside of the product_data object, into it, and it worked.
The code looks now like this:
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
export default async (req, res) => {
const { items, email } = req.body;
const transformedItems = items.map((item) => ({
// if quantities are bundled, this needs to change.
quantity: 1,
price_data: {
currency: 'usd',
unit_amount: item.price * 100,
product_data: {
name: item.title,
description: item.description,
images: [item.image],
},
},
}));
const session = await stripe.checkout.sessions.create({
line_items: transformedItems,
mode: 'payment',
success_url: `${process.env.HOST}/success`,
cancel_url: `${process.env.HOST}/checkout`,
metadata: {
email,
images: JSON.stringify(items.map((item) => item.image)),
},
});
res.status(200).json({ id: session.id });
};

Upload react-pdf dynamically generated file to Sanity using NextJS

I'm working on an e-commerce app built on NextJS and Sanity, so far I've made some mock products with all the necessary requirements, a user login system and checkout. I've been trying to make an invoice system so that when the user confirms an order 3 things must happen:
send all the order data to a react-pdf component and generate the invoice(working)
post the invoice file to the sanity schema so that the user has access to it when he goes to his order history page(not working)
email both the company and the client about the order(not implemented yet but I can do it)
ReactPDF allows me to access the pdf through a hook that returns me the blob of the file and the URL. I've tried to POST both of them but the url returned 404 and the blob didn't upload at all.
Searched the docs of both ReactPDF and Sanity and I couldn't find anything, although I think it has to do something with this endpoint from Sanity:
myProjectId.api.sanity.io/v2021-06-07/assets/files/myDataset
This is how I POST the order to my sanity studio
const { data } = await axios.post(
'/api/orders',
{
user: userInfo,
invoice_id: orders.length + 1,
orderItems: cartItems.map((item) => ({
...item,
slug: undefined
})),
billingData,
paymentMethod,
itemsPrice,
taxPrice,
totalPrice
},
{
headers: {
authorization: `Bearer ${userInfo.token}`
}
}
);
I've tried making 2 POST requests, one for the invoice_file alone, trying to post the blob or the url but none did work. The schema for invoice file was updated for the type of post each time so I'm 99% sure that wasn't the issue, anyway here's how the schema for invoice_file looks as for file:
{
name: 'invoice_file',
title: 'Invoice',
type: 'file',
options: {
storeOriginalFilename: true
}
},
If there would be any other code snippets relevant please let me know.
I really don't know how to find the solution for this as it's the first time trying to do such thing, so help would be much appreciated.
Thanks in advance!
I apologies as I'm not really active here but it's hard to pass on your question especially as I'm working on something similar. There's probably other ways to do this but I suggest you work use the official Sanity client. There's a specific section in the README that tells us how to do the file uploads or here.
So here's kinda the very small snippet:
import {
Document,
pdf,
} from "#react-pdf/renderer";
const doc = <Document />;
const asPdf = pdf([]); // {} is important, throws without an argument
asPdf.updateContainer(doc);
const blob = await asPdf.toBlob();
// `blob` here is coming from your react-pdf blob
const fileName = "customfilename.pdf";
client.assets.upload("file", blob, { filename: fileName }).then((fileAsset) => {
console.log(fileAsset", fileAsset);
// you can then use the fileAsset to set and reference the file that we just uploaded to our document
client.patch("document-id-here").set({
invoice_file: {
_type: "file",
asset: {
_type: "reference",
_ref: fileAsset._id,
},
},
}).commit();
});

Code was fine but not it's throwing error 403 - Failed to load resource: the server responded with a status of 403 (Forbidden) (Axios YouTube API)

I was following tutorial: https://blog.bitsrc.io/make-a-simple-react-app-with-using-youtube-api-68fa016e5a03.
I'm a noob so please, if you can help, pretend my name is Layman
I had actually finished, made it beautiful and was adding some additional things (like dislike buttons that dont do anything but look the part)
But now none of it works. I've even reverted my commits really far back to points where I know for show it works but I'm getting the same error. I can only assume its with youtube's api key but I dont know whats wrong. I noticed the issue when i tried to change the maxResults from 5 to 20. It did like that and it hasnt worked since.
I've made a new key, and used a try catch (i think ive done it right) and it still doesnt work
handle submit in App.jsx
handleSubmit = async (termFromSearchbar) => {
// alert(termFromSearchbar);
try {
const res = await youtube.get("/search", {
params: {
part: "snippet",
maxResults: 5,
key: process.env.REACT_APP_API_KEY,
q: termFromSearchbar,
},
});
this.setState({
videos: res.data.items,
selectedVideo: res.data.items[0],
});
} catch (error) {
console.error(error);
}
};
my .env file
import axios from "axios";
export default axios.create({
baseURL: "https://www.googleapis.com/youtube/v3",
params: {
part: "snippet",
maxResults: 5,
key: `${process.env.REACT_APP_API_KEY}`,
},
});
One possible explanation is that you've exceeded your quota (https://developers.google.com/youtube/v3/docs/errors)
You should verify that first. This document describes how you can do that (https://developers.google.com/youtube/v3/getting-started#quota)

Fetch status 200 but pending endllessly, except first call

I've been searching to solve this problem for a while but couldn't find a working solution.
I'm making a simple social network website and this API returns a article data such as text, image and video url, etc, all saved in server's local MySQL Database. My front-end is React and server is Nginx reverse proxy with Node.js using Express. When I load the page, I create 5 React components that each make fetch request for given article number.
The following code snippet is the fetch API that asks the server to fetch data from database:
//server-side script
app.get('/api/getArticle/:id', (req, res) => {
const con = mysql.createConnection({
host: 'myhost_name',
user: 'myUser',
password: 'myPassword',
database: 'myDB',
});
con.connect(function (err) {
if (err) {
throw err;
}
console.log("Connected!");
})
const idInterest = req.params.id.toString();
console.log(idInterest)
let sql = 'some_sql';
con.query(sql, function (err, result) {
if (err) {
res.status(500).send("Error while getting article data");
return;
}
else {
res.set('Connection', 'close')
res.status(200).send(result);
console.log("ended")
con.end();
return;
}
})
}
//React script
//index.js
fetch('http://mywebsite.com/api/getMaxArticleId/')//Retrieve top 5 article ID
.then((response) => {
for (let i = 0; i < data.length; i++) {
nodesList.push(<Container articleId={data[i]['id']}/>)
}
ReactDOM.render(<React.StrictMode><NavBar />{nodesList}<Writer writer="tempWriter" /></React.StrictMode>, document.getElementById('root'));
})
//Container.jsx; componentDidMount
const url = "http://mywebsite.com/api/getArticle/" + this.props.articleId.toString();
fetch(url, {
method: 'GET',
credentials: "include",
}).then((response) => {
response.json().then((json) => {
console.log(json);
//processing json data
This used to work very fine, but suddenly the getArticle/:id calls started to show 200 status but 'pending' in 'time' column in Chrome network tab, endlessly, all except the first*getArticle/:idcall. This prevents my subsequent .then() in each Container from being called and thus my entire tab is frozen.
Link to image of network tab
As you see from the image, all pending fetches are missing 'Content Download' and stuck in 'Waiting(TTFB)', except the first call, which was '39'
I checked the API is working fine, both on Postman and Chrome, the server sends result from DB query as expected, and first call's Json response is intact. I also see that console.log(response.json()) in React front-end shows Promise{<pending>} with *[[PromiseStatus]]: "Resolved"* and *[[PromiseValue]]* of Array(1) which has expected json data inside.
See Image
This became problematic after I added YouTube upload functionality with Google Cloud Platform API into my server-side script, so that looks little suspicious, but I have no certain clue. I'm also guessing maybe this could be problem of my React code, probably index.js, but I have no idea which specific part got me so wrong.
I've been working on this for a few days, and maybe I need common intelligence to solve this (or I made a silly mistake XD). So, any advices are welcomed :)

Why I got error: Cannot query field xx on type "Query"?

Although I copied and pasted the graphQL query from the GraphiQL tool after I tested it at GraphiQL successfully , the query returned with an error when I tried it in Apollo client within a reactJS app:
[GraphQL error]: Message: Cannot query field "allStudents" on type "Query"., Location: [object Object], Path: undefined
Here is my implementation:
const link = createHttpLink({
uri: 'http://localhost:8000/graphql',
fetchOptions: { method: "POST" }
});
const client = new ApolloClient({
link: link
});
const GET_STUDENTS = gql`
query getStudents($schoolID: Int!){
allStudents(schoolId: $schoolID){
pickUpLat
pickUpLng
}
}
`;
client
.query({
query: GET_STUDENTS,
variables: { schoolID: 1 }
})
.then(result => console.log(result));
What could be wrong? here is the correct response that I expected:
{
"data": {
"allStudents": [
{
"pickUpLat": 31.9752942479727,
"pickUpLng": 35.8438429235775
},
{
"pickUpLat": 31.9754545979993,
"pickUpLng": 35.8437478537235
}
]
}
}
EDIT
I get expected results using GraphiQL:
EDIT2
I tried to compare the payload between my request and GraphiQL request:
My request's payload: ( it has __typename which I don't know why )
{"operationName":"getStudents","variables":{"schoolID":1},"query":"query getStudents($schoolID: Int) {\n allStudents(schoolId: $schoolID) {\n pickUpLat\n pickUpLng\n __typename\n }\n}\n"}
GraphiQL request's payload:
{"query":"query getStudents($schoolID: Int!){\n allStudents(schoolId: $schoolID){\n pickUpLat\n pickUpLng\n }\n}","variables":{"schoolID":1},"operationName":"getStudents"}
So, they are almost identical, Any idea?
The fault with my query was that I didn't download the new schema.
You can download the schema by using: apollo schema:download --endpoint=http://localhost:8080/graphql schema.json
replace http://localhost:8080/graphql with your server endpoint
You can see more at https://www.apollographql.com/docs/ios/downloading-schema/
In my case, I had defined a query which didn't require any parameters and it would return an array of objects:
myBasicQuery: [BasicAnswer]
type BasicAnswer {
name String
phone String
}
I was getting the error: Cannot query field \"BasicAnswer\" on type \"BasicAnswer\" when I declared it like this:
query myBasicQuery {
BasicAnswer {
name
phone
}
}
Leaving only the fields of BasicAnswer fixed the issue:
query myBasicQuery {
name
phone
}
For anyone else who might be searching for this problem, make sure you're importing ApolloClient from apollo-client package and not other packages.
For anyone that follows apollo-client has now been sunset, in favour of #apollo/client
Here is how you should be constructing a query
Updated #graphql-codegen/cli package to latest version(2.6.2) and it's working fine.
For anybody who use hasura also.
Problem was
query: query_root
# query: Query # wrong value before upgrade
mutation: mutation_root
subscription: subscription_root
}```
Take a look at your entity, it may be missing the #Field() annotation.
Example:
#PrimaryGeneratedColumn()
id: string;//Will not be mapped by GraphQL and you will get OP's error
#Column()
#Field()
name: string;//Will be mapped by GraphQL and you will not get OP's error
This also happens, if you have fragmented your graphqls files and you forgot to define it in codegen.ts.
(java-project)/src/main/resources:
schema.graphqls
search.graphqls
(angular-project)/codegen.ts
const codegen: CodegenConfig = {
overwrite: true,
// add wildcards here, to read all files:
schema: "../projectname/src/main/resources/graphql/*.graphqls",
documents: './src/app/core/graphql/*.ts',
generates: {
....
}
}
If you see this issue in the GraphiQL interface, you may need to merely refresh the page, which downloads the new schema and the error goes away.

Resources