How to run Mongo JS Shell Script with DB Connection - javascript

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.

Related

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

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.

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.

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.

How can I initialize MongoDB -object db in a browser console?

Suppose I want to execute 'db.things.insert({colors : ["blue", "black"]})' in browser. I can execute it in the Mongodb -shell but not yet understanding how to execute it like: open up the Google Chrome Console, initialize the DB -object with some connection and execute the command. Does there exist some plugin? Sorry I am totally new to MongoDB, trying to test just things fast with Browser shell. How can I do the initialization like that?
Trial 0: perhaps with REST -interface?
I have enabled the REST with "$ echo 'rest=true' > /etc/mongodb.conf;
$ sudo restart mongodb", works in Ubuntu. More about rest
here, not sure
yet whether needed here but perhaps with some POST/REST -method I can
do the init.
Trial 1: Oreilly's book about MongoDB and 50 Tips (page 47)
The book has some example
> db = connect ("ny1a:27017/foo")
> db = connect ("ny1a:27017/admin")
so now
> db=connect("localhost:27017/test")
ReferenceError: connect is not defined
Yes because I need to source the connect -command, some further examples here, where can I get it?
P.s. I am studying this tutorial here.
You cannot simply access mongodb from the browser console. Your browser is a client, and there isn't (as far as I know) a javascript client-side library. Any javascript library you will find will most likely be for Node.js (server).
The mongo console is its own type of compiled client. The native language is javascript, but those commands only pertain to the actual mongo command shell. connect is a command for the mongo command shell.
Enabling REST starts a port on your mongod that will accept REST http communication. You get a browser page here: http://localhost:28017/
This is a very basic page displaying data, but you can further run queries yourself. See http://www.mongodb.org/display/DOCS/Http+Interface#HttpInterface-SimpleRESTInterface
Note, the REST interface is READ ONLY. You cannot insert.
That being said, you need a proper driver for your language of choice.

Node.JS MongoDB Order of Operations Use Case

What is the order of operations for the mongodb-native driver?
Let's say you have a class that's purpose is to save a document of some sort and let's say it has a long life. How many times should open be called? Once per db write? When is close supposed to be called? Essentially I want a class method that looks like this:
var myMongoClass = new MongoDB(server,port)
myMongoClass.write_file(filename,callback)
myMongoClass.write_doc(doc,callback)
I posted this a while ago and got it working:
Problem with MongoDB GridFS Saving Files with Node.JS
It's now not working at all and failing with TypeError: Cannot read property 'md5' of null
Every time I work with this library I want to bang my head through a wall.
It seems like the correct answer is create a client and keep that client open for the duration of the application (never explicitly calling close). I have a wrapper that keeps a reference to the connected client and my app only boots up if the connection is received.

Categories

Resources