My goal is to update values that stored in MongoDB, therefore I have decided to use mongoose to see data and edit them, However; it gives me an error.
Maybe I am in the wrong way, does anybody has already implemented this kind work.
import * as React from "react";
import * as mongoose from 'mongoose'
export interface State {
}
export default class mongodb extends React.Component<State> {
constructor(props: {}) {
super(props);
}
private setupDb() : void {
var mongoDb = 'mongodb://localhost/My_db';
mongoose.connect(mongoDb);
console.info("Connected to Mongo.")
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB Connection error'));
}
componentDidMount(){
this.setupDb()
}
render() {
return (<div></div> );
}
}
The error:
TypeError: mongoose__WEBPACK_IMPORTED_MODULE_1__.connect is not a
function
It looks like you're trying to connect to the database from the application frontend. You need to do this in the backend.
In your backend, make sure you run npm install mongoose. Once that is done, I think your code will execute without any problems. Alternatively, this is how I've done it:
var mongoose = require("mongoose");
const connect = () => {
mongoose.connect("mongodb://[username]:[password]#1[host]:[port]/[database]");
//e.g. "mongodb://My_db_user:pw1234#localhost:27017/My_db"
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function() {
console.log("Connected to mongo..")
});
};
Followed by a call to connect() somewhere in your startup script.
If you don't require any authentication for accessing your database, and you're running on the default port of 27017, you should be able to use your connection URI (mongodb://localhost/My_db).
package shipped to frontend by mongoose does not have the connect function.
you can only connect using a backend.
see here
Calling mongoose from react client side
Related
I just started with Next js. The question I have is that in express projects we have a connection to the database once and we put it in the main file of the program, i.e. app.js. but in Next js as I understand so far, the connection to the database must be inside the api file. Doesn't this cause the connection to be reconnected every time the api is called? Is it necessary to have a file like app.js in order to connect to mongo inside it?
thanks
create one separate file and add following code in that file.
import mongoose from 'mongoose';
const connection = {}
const dbConnect = async () => {
if (connection.isConnected) return
const db = await mongoose.
connect(process.env.DB_URL, { useNewUrlParser: true, useUnifiedTopology: true })
connection.isConnected = db.connections[0].readyState
}
export default dbConnect
now only you need to call dbConnect() function every where you are performing the db operation.
Just started using the Realm MongoDB and i watched this video https://www.youtube.com/watch?v=Evp3xTzWCu4 from MongoDB and followed exactly what he did, but for some the function on the client side is not working. I'm using Expo React Native
I have this simple Realm function
exports = function(arg){
var collection = context.services.get("mongodb-atlas").db("questiondb").collection("questions");
collection.insertOne({name:arg}).then((doc) => {
console.log('Success')
}).catch(error=>console.log(error))
};
When i call it in the real console, it works fine.
This is the front end function
const connectDB = async () => {
const appID = "myapp-ckwfl";
const app = new Realm.App({ id: appID });
const credentials = Realm.Credentials.anonymous();
try {
const user = await app.logIn(credentials);
await user.functions.addQuestion("Myself");
console.log("Logged in");
} catch (error) {
console.log(error);
}
};
I'm getting the 'Logged in' in the console.
I went to check the activity log on the MongoDB atlas and it shows OK to both login and function
However, the function log shows me this message
[ "FunctionError: can't find a table mapping for namespace questiondb.questions" ] { "name": "addQuestion" }
And i have the database 'questiondb' with the collection 'questions'.
What am i missing here?
I ran into a similar error. The problem was that my BSON did not contain an "_id" field. But the BSON validation when saving it allowed me to save the schema like that. But when querying data through graphql I got this exact same error. So the solution was to fix the BSON schema. Even if the BSON schema saves and deploys successfully it can still be that it will not work for graphql.
You can see if your BSON has errors by navigating here:
So I have been following other Q&A on stackoverflow and AWS SDK docs but I still couldn't delete S3 files with the following code, it simply gives the following error Error TypeError: Cannot read properties of undefined (reading 'byteLength')
My code (s3Client.js):
import { S3Client } from "#aws-sdk/client-s3";
const REGION = `${process.env.S3_UPLOAD_REGION}`;
const creds = {
accessKeyId: process.env.S3_UPLOAD_KEY,
secretAccessKey: process.env.S3_UPLOAD_SECRET
};
// Create an Amazon S3 service client object.
const s3Client = new S3Client({
region: REGION,
credentials: creds
});
export { s3Client };
My nextJS component:
import { DeleteObjectCommand } from "#aws-sdk/client-s3";
import { s3Client } from "../lib/s3Client.js"
const bucketParams = { Bucket: "my bucket name...", Key: "my key..." };
const run = async () => {
try {
const data = await s3Client.send(new DeleteObjectCommand(bucketParams));
console.log("Success. Object deleted.", data);
return data; // For unit tests.
} catch (err) {
console.log("Error", err);
}
};
I understand from others that this seems like a credential issue but I still couldn't wrap my head around where the problem is.
Edit:
Solution to this problem -
Check the .env, depending on whether you are using React or NextJS, you will need to have either "REACT_PUBLIC" or "NEXT_PUBLIC" in order for the environment objects to be exposed via process.env.
Check your permission in your S3 bucket and set "AllowedOrigins" to include your localhost. I had mine set as "AllowedOrigins": "*" but it wasn't enough. So I have included http://localhost:3000 and it worked.
So it looks like that you're using keys credentials for this. To debug your problem the 1st thing you should do is to check the credentials outside code and SDK and make sure they're fine.
To do this, setup the credentials on CLI by setting environment variables.
export AWS_ACCESS_KEY_ID=<Your Key here>
export AWS_SECRET_ACCESS_KEY=<SECRET HERE>
export AWS_DEFAULT_REGION=<AWS REGION>
Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html
After this run this command to verify credentials are setup correctly aws sts get-caller-identity
If they show you the account and user details. Then delete the file using CLI. If that works then it is confirmed that issue is not with the credentials and with code. If not, it will point you in the right direction where the issue is.
import React, { Component } from 'react';
import tableau from 'tableau-api';
class App extends Component {
componentDidMount() {
this.initViz()
}
initViz() {
const vizUrl = 'http://public.tableau.com/views/RegionalSampleWorkbook/Storms';
const vizContainer = this.vizContainer;
let viz = new window.tableau.Viz(vizContainer, vizUrl)
}
render() {
return (
<div ref={(div) => { this.vizContainer = div }}>
</div>
)
}
}
export default App;
it works when i publish my workbook to public tableau with extract data source
but when i publish the same in tableau with live data source(sql),
I obtained a url,
https:///#/site/testsite/views/genderanalysis/Sheet2?:iid=1
and that when i used here not working
and from the doc, i found api with unique-token
https:// /trusted/%3CTRUSTED%20TICKET%20HERE%3E/t/testsite/views/genderanalysis/Sheet2?:embed=yes&:comments=no&:toolbar=yes&:refresh=yes&:embed=y&:showVizHome=n&:jsdebug=y&:bootstrapWhenNotified=y&:apiID=handler0
But i dont know how to generate unique-token
when i browse it on a website it shows token error
i used https:///trusted/ with username as param, but it always returns -1
im using trial version
Did this worked for anyone?
It looks like you are trying to use Trusted Authentication but haven't done the steps necessary to create and use tokens. First, you need to configure Tableau Server to accept and trust requests from the server you will be embedding the dashboards in. Once you've done that you will be able to make POST requests for tokens from your web server. That is the time you use the username and other parameters. You will then receive a token that you can use to construct the URL for the view. Hope this helps!
I am fairly new to React, and have not done any extensive web development in years, so am struggling with a (probably) basic web issue:
I am implementing a Stripe based payment flow in a React web app (written in Typescript), and have hit a roadblock on step 2 (adding a redirect to checkout client-side).
The quickstart guide instructs me to insert the following script tag on my website, which I have done through inserting the tag inside the <head> tag:
Checkout relies on Stripe.js. To get started, include the following
script tag on your website—it should always be loaded directly from
https://js.stripe.com:
<script src="https://js.stripe.com/v3/"></script>
The next step is where I am having a problem (using the ESNext syntax since this is in a Typescript project):
Next, create an instance of the Stripe object by providing your publishable API key as the first parameter:
const stripe = Stripe('pk_test_sdjxyNjHWmRefdkUNYuS53MA00Ot1f9HOu');
I would like to access Stripe through a service worker, rather than a component directly. However, trying to initialise the stripe instance is not working. I have tried:
importing the Stripe module in various ways, which hasn't worked
adding a dependency on #types/stripe, which seems to prevent the compiler complaining
Currently, my StripeService.ts file has the following code:
const stripe = Stripe("SOME_KEY");
export const redirectToCheckout = (sessionId: string) => {
return stripe.redirectToCheckout(
{
sessionId: sessionId,
});
};
Localhost instance is giving this error:
/src/services/stripe/StripeService.ts
Line 12: 'Stripe' is not defined no-undef
Any suggestions on how I can resolve this issue? I have looked into the react-stripe-elements wrapper, but that is geared towards providing UI components, whereas I only want the Stripe checkout API call behaviour.
Bare Minimum
Minimum implementation is to declare Stripe using any:
declare class Stripe {
constructor(...args: any[]);
redirectToCheckout(...args: any[]): any;
}
const stripe = new Stripe("pk_test_sdjxyNjHWmRefdkUNYuS53MA00Ot1f9HOu");
stripe.redirectToCheckout({
sessionId: sessionId
})
Stronger Typings
You can of course expand this by more explicitly typing the parts that you need:
declare class Stripe {
constructor(publicKey: string);
redirectToCheckout({
sessionId
}: {
sessionId: string;
}): Promise<{ error: Error }>;
}
const stripe = new Stripe("pk_test_sdjxyNjHWmRefdkUNYuS53MA00Ot1f9HOu");
stripe.redirectToCheckout({
sessionId
}).then(function (result) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `result.error.message`.
});
Try using the windows object instead:
var stripe = window.Stripe("pk_test_h4naRpZD1t2edp2HQKG2NrZi00rzz5TQJk");
For a service file, you would just add stripe to package.json, then in the file would do:
import Stripe from "stripe";
const stripe = Stripe("SOME_KEY");
export const redirectToCheckout = (sessionId: string) => {
return stripe.redirectToCheckout(
{
sessionId: sessionId,
});
};
You would use the public key in the client side, and the secret key in the server side. You should keep stripe object (Stripe('pk_test_sdjxyNjHWmRefdkUNYuS53MA00Ot1f9HOu')) in your state somehow to be able to retrieve it later.
An example call could be like this:
client side
const {paymentMethod, error} = await this.state.stripe.createPaymentMethod('card', cardElement, {
billing_details: {
name: 'Jenny Rosen',
},
});
StripeService.makePayment(paymentMethod);
server side
import Stripe as "stripe";
const stripe = Stripe("SOME_KEY");
export const makePayment = (paymentMethod: object) => {
...
};