How to import a Javascript Object in mongo shell script - javascript

I have a shell script file called run.sh
CONNECTION_STRING="mongodb://localhost:27017/"
mongo --nodb --eval "var connectionString=\"$CONNECTION_STRING\"; `cat mongo-initialize.js`"
I'm passing a js fragment to the mongo shell. This is my mongo-initialize.js:
conn = new Mongo(connectionString);
db = conn.getDB("dbName");
db.createCollection("collection");
db["collection"].insertMany(data);
The data I'm using to insert into the collection will be a js object which I'm planning to use here and I need it for an API as well. So I created a js file mock.js which has that object and I exported it. The thing is I don't find an appropriate command to import the data in my mongo-initialize.js.
The only command MongoDB docs suggest is load('someFile.js') which is not working in my case. As per MongoDB docs, it executes the js file and it throws an error if I try to load it this way.
This function loads and executes the myjstest.js
Is there a way to import a js object into my script file?

Related

Call a java script file in mongodb shell

I tried to run a JS file directly from the Mongo shell by using the query
mongo localhost:27017/west createSumCollection.js
However I keep getting the error
"uncaught exception: SyntaxError: unexpected token: identifier :
#(shell):1:6"
The contents of CreateSumCollection.js are a simple use database and db.createCollection with a simple object id and another field.
Any idea what I am missing here? If I run the same script in the mongoshell directly it works perfectly.
I tried load("C:/mongodb/data/db/createSumCollection.js") and it failed because of the use west statement inside the .js file. So after removing that, the load worked. My question is what is the difference between load and mongo localhost:27017/west createSumCollection.js and how do i get the js to be run directly.
use is a helper that is only available in the interactive shell.
In the interactive shell (and via load) you might run:
use my_database
db.collection.find()
The equivalent in a javascript file on the command line would be:
db.getSiblingDB("my_database").collection.find()

Fetching a json outside of react root

I've got a project which has an "old" javascript/php app. It contains dozen of json files for getting data from the database.
Besides that I'm going to migrate some modules to react but still want to use those json files for now. Is it possible to fetch the json files from the react app? Both apps are in the same repository.
Lets pretend you have this folder structure:
/
/LegacyApp
/LegacyApp/file.json
/NewApp/index.js
Then you can simply import the files from your new app via the require function:
// inside index.js
const data = require('../LegacyApp/file.json')
// Or newer ES6 Syntax
import data from '../LegacyApp/file.json'
That JSON-file will be imported as a JavaScript object.

Trying to use pouchDB, saying that it's not defined when i think it is

i'm trying to add pouchdb to my pwa to store some things when offline so i can post them later. I first register my Service Worker from app.js, and from it i ImportScript two other files with the logic of the sw. One of those files is where i put the logic for the db, sw_db.js. I installed pouchDB with npm and added the script tag for it in index.html but i when i declare:
const db = new PouchDB('acciones');
i get
sw_db.js:4 Uncaught ReferenceError: PouchDB is not defined
at sw_db.js:4
at sw.js:3
Basically, sw_db.js doesnt know about PouchDB even though the methods from pouchdb get autocompleted. i've tried adding the cdn or downloading the file but still doesnt work. Also the script tag for pouchdb is before app.js in index.html (which registers the sw).
I am not sure if you are using PouchDB in a browser or a NodeJS context. If it is in a browser, then the PouchDB module should be defined in the HTML file like this:
<script src="js/pouchdb.min.js"></script>
assuming you have the PouchDB module on your web server. If not you can use it from a CDN like this:
<script src="//cdn.jsdelivr.net/npm/pouchdb#7.1.1/dist/pouchdb.min.js"></script>
and your Javascript code should work:
const db = new PouchDB('my-db');
But if it is in a NodeJS script then you need to install PouchDB with npm as you mention and declare it in the code like this:
const PouchDB = require('pouchdb');
and then define a database the same as before:
const db = new PouchDB('my-db');
I hope this helps you resolve the error.

Accessing prototype function from node modules

I need to implement 3rd party rest API in php project for integrating another project which is in angular.
Using rest API, I need to store cookie in the browser and cookie value will be in a specific format as instructed for which I need to import a specific npm package called angular2-cookie inside my root directory from
https://github.com/salemdar/angular2-cookie/blob/master/src/services/cookies.service.ts
I successfully installed it using npm command inside root directory.
In /js/sample-script.js
I imported the specific cookies.service.js file from that angular2-cookie module using browserify lib like
var CookieService = require('../node_modules/angular2-cookie/services/cookies.service');
var cs = new CookieService();
cs.putObject('somecookie',{user: 'john'});
but in the console, I am getting an error like:
Uncaught TypeError: CookieService is not a constructor
How can I implement putObject method from CookieService prototype?
Note: There is no error coming till 1st line where I used require method

How do I handle command-line arguments in a mongo script?

I've been working on some simple scripts to run on mongo from the bash command-line. Originally, I ran them as follows:
$ mongo dbname script.js
but I recently came across mikemaccana's answer, https://stackoverflow.com/a/23909051/2846766, indicating the use of mongo as an interpreter so I can just execute script.js (or any name I choose, with or without the .js) from the command line.
$ script.js
I think it's brilliant and clean, but now I'd like to pass in a database name as a command line argument.
$ script.js dbname
Here I use the bash-style "$1" to demonstrate what I'm doing in script.js.
#!/usr/bin/env mongo
var db = new Mongo().getDB($1);
// Do other things with db, once I resolve the name from the command line.
This results in a "ReferenceError: $1 is not defined ...", which is not surprising. But how would I reference command line arguments? Is this going to be a mongo convention? a javascript convention? Is it possible? It would make my command-line experience with mongo much better aesthetically.
Currently there is no way to do this using the mongo shell...
https://groups.google.com/forum/#!topic/mongodb-user/-pO7Cec6Sjc
... try using a bash script (or other scripting language you are comfortable with) if you want to get a similar command line experience.
Duplicate of How to pass argument to Mongo Script
In a nutshell, this is not possible but several workarounds are given in the answers (not repeated here).
You can pass args to your script through
mongo --eval 'var databasePassword="password"' script.js
and you can access databasePassword value inside script.js
db.auth({ user: 'testUser, pwd: databasePassword });

Categories

Resources