How can I reference data from MariaDB on web browser JS application? - javascript

I am trying to create a webpage that uses data from a MariaDB. My current idea (which has been giving me a lot of trouble) is to just connect to the database from the app.js file, which is the main script for my index.html.
const dotenv = require("dotenv");
dotenv.config();
const mariadb = require("mariadb");
const pool = mariadb.createPool({
database: process.env.DATABASE,
host: process.env.HOST,
user: process.env.USER_TOKEN,
password: process.env.PASSWORD,
});
// the rest of the code involves selecting from the db, and parsing the data
However, I have been running into many issues. I'm not too knowledgeable on all this, but I found that I need to webpack the file if I want to be able to use the "require" keyword. But I could not figure that out as I kept running into weird issues when using Browserify; I think there may be an incompatibility with MariaDB. I also looked into using JS modules, but I am not sure if that is possible with MariaDB.
I am trying to come up with another solution, potentially using some sort of API to a back end, which would make the GET request to the database, but I feel like it should not have to be that complicated for my sake (I also wouldn't really know where to start with this). All I basically want to do, is make a GET request to a MariaDB when the page loads on the client's browser and display that data on the webpage. Is there a simple way to do this?

I suggest you use nodejs to connect and query database as it will greatly resolve a lot of overhead for you..
The easiest way i can think of is using a prisma starter template here
https://github.com/prisma/prisma-examples/tree/latest/javascript/script
It also gives the added advantage of the ORM function...
Hope it helps.

Related

How to pull data from the Directus database to the site?

I created a database in Directus. I created a separate project for the site, where I will add data. Installed # directus / sdk.
image
But when importing, I get an error
Uncaught SyntaxError: Cannot use import statement outside a module
this is my code
import { Directus } from '#directus/sdk';
const directus = new Directus('https://api.example.com/');
await directus.auth.login({
email: 'admin#example.com',
password: 'pass',
});
const articles = await directus.items('articles').readMany();
console.log({
items: articles.data,
total: articles.meta.total_count,
});
How do I fix this error?
Is it correct to create a separate project for the site? Or could it be done in the same place as the database?
TLDR; The issue faced is does not appear to be an issue with Directus.
There are three different pieces of software/code that that you should be aware of.
Database.
Directus Install.
Your App.
These are three different things, make sure you're clear on the difference. The database will be stored in your database of choice, MySQL, Postgres etc... Directus only connects to this and it will remain should you decide to stop using Directus for any reason.
You will need to install Directus in one location. You will then need to write your application in another location, where you may use the SDK for easy Directus API usage within your app.
It is correct (as you asked) to have your application as a separate "project".
The reason you are getting the error Cannot use import statement outside a module is not related to Directus. This is a common error when you are building or compiling your application incorrectly (Not ES6) therefore I cannot provide much support to you.
Here are some helpful debugging resources:
https://www.google.com/search?q=cannot+use+import+statement+outside+a+module
"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6
https://exerror.com/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-importing-ecmascript-6/

Node Backend Application Database Connection Objectorientated

I am working on a backend application with node using typescript / javascript. My backend is using a sqlite database. I structured my project so that there is one file that contains all the database logic.
I could either write a module that will be required by all modules that or I could write a class which connects to the database in the constructor.
For me it seems a little bit weird to pack all database logic in a module that is not an object. What is the best practice in this case and why? (I know this might be a stupid question but I'm just a hobbyist)
Thanks in advance
In my case I make the connection to the database before running the server. In pseudocode:
connectorDB.connect( path, config, () => {
server.listen( port )
})
It will depend on how important the database connection is in the operation of your app.

How to run Mongo JS Shell Script with DB Connection

I'm trying to write a mongo shell script that will delete some entries in an existing DB, and then reload them (depending on some conditions), and I'm having a lot of trouble.
One thing I can't understand/figure out is this:
To run the script file I'm making (let's call it script.js), I'm reading (from mongo docs and other places) that I need to use a command like this:
mongo mongodb://{{mycreds}}#{{address of existing mongo}}:27017/{{DB I want}}?authSource=admin script.js
However, since I'm connecting to that same DB in the script itself, I'm also seeing that I need to make that connection in the script.js:
db = connect(
"mongodb://{{mycreds}}#{{address where the existing mongo is}}:27017/{{DB I want}}?authSource=admin"
);
Why do I have to specify the DB connection when running the script? It's in the script?
Either way, I'm not able to make the connection in the script. I don't know if I'm running the script incorrectly, or making the connection to the DB in the script incorrectly. Or just something else.
In the docs, it says I can run the script in the mongo shell as well. But don't I have to have a mongo instance running at 27017 to start the script? And do I need a mongo running on my machine (since there's already one that exists that I need to connect to)?
I would really appreciate some clarity in this. All I'm trying to figure out is how to run a mongo script that connects to an existing DB, and I'm getting really tangled in all these docs.
Edit:
After receiving a comment (thanks Joe), I removed the connection in the script file and was able to make the connection. I guess having both was messing it up. I'd still like to be able to have the connection in the script, but not when I run the script.
I want to do this so that others can run the script without entering the long connection address.
If anyone knows a way to do this, I'd appreciate the help. Thanks.
you always need a credential for any DB you want to connect even if it's SQL. if you want to make it easier for you, you need to create a file.js in vs code and put a credential in a file when you need it you can just call it that's it, and use roboMongo to make your life easier with MongoDB.

What is the right way to manage connections to mongoDB, using node?

I'm using node.js and mongoDB. Right now, for my test app, the connection to the db is in the main node file, but I guess this is a wrong practice.
What I want/need: a secure way (i.e. not storing password on files users can access) to connect to the db just when needed.
For example: I want several admin pages (users, groups, etc..). Each page should connect to the db, find some data, and display it. It also have a form for adding a document to the db and a delete option.
I thought maybe to create some kind of a connection function - send it what you want to do (add, update, find, delete), to where (collection name) and whatever it needs. But I can't just include this function, because then it'll reveal the password to the db. So what can I do?
Thanks!
I'm going to answer your question bit by bit.
Right now, for my test app, the connection to the db is in the main node file
This is fine, though you might want to put it in a separate file for easier reuse. NodeJS is a continuesly running process, so in theory you could serve all of your HTTP responses using the same connection to the database. In practice you'd want to create a connection pool, but the Mongodb driver for NodeJS already does this automatically.
Each page should connect to the db, find some data, and display it.
When you issue a query on the MongoDB driver, it will automatically use a connection from its internal connection pool, as long as you gave it the credentials when your application was starting up.
What I want/need: a secure way (i.e. not storing password on files users can access) to connect to the db just when needed.
I would advice to keep your application configuration (any variables that depend on the environment in which the app is running) in a separate file which you don't commit to your VCS. A module like node-config can help a great deal with that.
The code you will end up with, using node-config, is something like:
config/default.json:
{
"mongo": null
}
This is the default configuration file which you commit.
config/local.json:
{
"mongo": "mongo://user:pass#host:port/db"
}
The local.json should be ignored by your VCS. It contains secret sauce.
connection.js:
var config = require('config');
var MongoClient = require('mongodb').MongoClient;
var cache;
module.exports = function(callback){
if(cache){
return callback(cache);
}
MongoClient.connect(config.get('mongo'), function(err, db){
if(err){
console.error(err.stack);
process.exit(1);
}
cache = db;
callback(db);
});
}
An incomplete example of how you might handle reusing the database connection. Note how the configuration is gotten using config.get(*). An actual implementation should have more robust error handling and prevent multiple connections from being made. Using Promises would make all that a lot easier.
index.js:
var connect = require('./connection');
connect(function(db){
db.find({whatever: true})
});
Now you can just require your database file anywhere you want, and reuse the same database connection, which handles pooling for you and you don't have your passwords hard-coded anywhere.

AngularJS - Interaction with mongodb

I am new to MEAN stack, I am trying to create a basic one page application at the moment.
I am trying to connect to the mongodb and then list the values in a certain collection in a controller.
However, when I looked for the answer, I came across this answer
Using AngularJs and MongoDB/Mongoose
Which then confuses me as what is the point of having the code below if you can't use it between angular and mongo ? Or are there other interim steps that use it?
var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://localhost:3000/database');
var orderSchema = new mongoose.Schema({
routeFrom : String,
routeTo : String,
leaving: String
});
var Order = db.model('Order', orderSchema);
module.exports = Order;
Edit: The situation i am trying to use it in is such:
Geek.html
<div class="jumbotron text-center">
<h1>Geek City</h1>
<p>{{tagline}}</p>
<ul>
<li ng-repeat="value in dataValues">
{{value.name}}
</li>
</ul>
</div>
GeekController
angular.module('GeekCtrl', []).controller('GeekController', function($scope) {
$scope.tagline = 'The square root of life is pi!';
$scope.dataValues = function(){
var mongo = require('../config/db.js');
var collectionValues = mongo.myCollection.find();
return collectionValues;
};
});
You cannot require db.js config file in Angular because it's not set to be used on the client side. What you describe is so called 'Isomorphic' approach.
What I mean by that: mongo is a database system (roughly speaking). To get data from the database, we usually don't trust the client. So we have some server-side code (PHP, Ruby, Node.js, Java, what have you) which authorizes the client, processes and filters the data and returns it to the client (in this case Angular.js). So your Mongoose models are set to be used by the server-side javascript and that part of the app. That server side should also serve data to Angular so you'd connect to Node.js from Angular, not directly to Mongo. So the same server that (usually) serves your angular files, will also serve the data it reads from mongo.
If you want server-less data with Angular, you can take a look at Firebase.js. It's angular-ready and it could help you not mess around with Mongo, mongoose and the server-side code.
You could try a hybrid approach with something like meteor.js or backbone.js set to work both on client and server, or take a look at this article for more info.
Or for what it's worth, if you want to run your own Mongo, you could start mongo with --rest, then you'd be able to connect to Angular directly to Mongo, at http://somehost:28017/mydatabase or something similar, depending on your setup.
Mongoose is a node module, and as far as I know it doesn't have a front end component, so you won't be using it directly in your frontend js code. It's only going to help you on the server side of your app. If you're relatively new to Node then this stuff can get pretty confusing, since it's all end-to-end javascript and sometimes it's not clear what modules work on the server or frontend, especially since some can do both.
Node, MongoDB, Express, and Mongoose all live on the server.
Angular lives in the browser, and can't use any of the server-side components directly.
Using the MEAN stack, You will be building a node app that uses mongoose to talk to mongodb and express to expose an api to your front end. Then in in your html/js code you'll be using angular and its $http service to talk to the server to get and set data.
There is a great tutorial that walks you through the entire process on scotch.io:
http://scotch.io/bar-talk/setting-up-a-mean-stack-single-page-application

Categories

Resources