how to write a script file which can run multiple nodejs program - javascript

I have few java script files which will push some initial configuration data to the database one of the sample file is shown below
var mongoose = require('mongoose'),
config = require('../../config/config');
var PassportLocalUser = require('../models/Passport_LocalUsers');
Schema = mongoose.Schema;
mongoose.connect(config.db);
PassportLocalUser.findOneAndRemove({"username": 'admin'}, function(err){
if(err) {
console.log(err)
}else{
console.log("removed previous admin document ")
PassportLocalUser.findOneAndRemove({"username": 'user'}, function(err){
if(err) {
console.log(err)
}else{
console.log("removed previous admin document ")
generateUserCredentials();
}
});
}
});
function generateUserCredentials(){
var userObj = new PassportLocalUser();
userObj.username="admxcvin";
userObj.password="$2a$10$7/xcvxcvxcvzyPNb1XxbAKG2INj4/R.TYrn0a.k9jrLvrifiV/V6RDxhpTaht6";
userObj.save(function(err,result){
generatePublicUserCredentials();
if(err)
console.log(err)
console.log("Credencials generated")
})
};
function generatePublicUserCredentials(){
var userObj = new PassportLocalUser();
userObj.username="user";
userObj.password="$2a$10$JzLQmIThoU4swr36KUmcAO5QK5.J529qW5saO36jzgShKJV/EfBsi";
userObj.email="user#gmail.com";
userObj.firstName="user";
userObj.lastName="user";
userObj.save(function(err,result){
if(err)
console.log(err)
console.log("Credencials generated")
})
}
now in order to save the data by these multiple files
I type explicitly has node fileName.js Which will generate the data
But now looking for a script which will help me to run all generators at one shot.
ie, if a folder name generator has few file like settingsConfigurationGenerator.js, user.js ..........
all these files should run or execute using single script file please provide some pointers to accomplish it.

Related

Strapi uploaded files are not displaying on website

I have many files which are stored in upload_file collection in mongodb and they have relations with related content types. However when I open Strapi CMS UI, I cannot see the file attached on its content type.
I am using Strapi v3.4.6 — Community Edition.
In the first picture is showing the my one of upload_file collection item. Its relation is shown in red circle.
In the second picture is showing the my main content type collection item. You see that its id and upload_file rel id is matching.
But in Strapi UI, this file is not linked to model. The file exists in file system of Strapi. However it is not visible
I can add this file manually, but is there any quick way to do this?
You need to migrate the database. We solved with a basic script.
Run http://localhost:3000/migrate
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017";
var dbName = "YOURDBNAME";
const express = require('express')
const app = express()
const port = 3000
var _db;
var _dbo;
var tables = {
"table1": "TabLE1",
"table2": "TABle2",
}
app.get('/migrate', (req, res) => {
res.send('Started!')
_dbo.collection("upload_file").find({}).toArray(function(err, result) {
if (err) throw err;
result.forEach(function (item) {
if (item.related.length > 0) {
var related = item.related[0];
var query = { '_id': related.ref };
var newvalues = { $set: {} };
newvalues.$set[related.field] = item._id;
var tableName = related.kind.toLowerCase();
_dbo.collection(tables[tableName]).updateOne(query, newvalues, function(err, res) {
if (err) throw err;
console.log(res != null ? res.ops : null);
});
}
})
// db.close();
});
})
MongoClient.connect(url, function(err, db) {
if (err) throw err;
_dbo = db.db(dbName);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// Run http://localhost:3000/migrate
When uploading your image to strapi make sure your formData has these fields
const formData = new FormData();
formData.append('files', image);
formData.append('ref', 'contentTypeName');
formData.append('refId', dataItemId);
formData.append('field', 'image');

Express js,mongodb: “ReferenceError: db is not defined” when calling a function

The code is set up this way:
var express = require('express');
var router = express.Router();
var mongo = require('mongodb').MongoClient;
function getData(){
db.collection("collection_name").find({}).toArray(function (err, docs) {
if (err) throw err;
//doing stuff here
}
var dataset = [
{//doing more stuff here
}
];
});
}
router.get("/renderChart", function(req, res) {
mongo.connect(url_monitor, function (err, db) {
assert.equal(null, err);
getData(res);
});
});
When I run the code and trying to get to /renderChart when running, I get the "ReferenceError: db is not defined". I came across a similar case, and think it may be a similar problem caused because mongodb.connect() is called asynchronously, but I couldn't get it to work:
Express js,mongodb: "ReferenceError: db is not defined" when db is mentioned outside post function
The problem here is you don't pass the db to the function, so it's undefined.
A solution:
function getData(db, res){
db.collection("collection_name").find({}).toArray(function (err, docs) {
if (err) throw err;
//doing stuff here
}
var dataset = [
{//doing more stuff here
}
];
});
}
router.get("/renderChart", function(req, res) {
mongo.connect(url_monitor, function (err, db) {
assert.equal(null, err);
getData(db, res);
});
});
You'll probably need to pass the req at some point too, or make specific db queries. And you'll probably want to use promises or async/await to better deal with all asynchronous calls.
Its Simple Javascript.
You are using a variable db in your file, which is not defined, so it will throw an error.
You need to do something like this .
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Find some documents
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
assert.equal(2, docs.length);
console.log("Found the following records");
console.dir(docs);
callback(docs);
});
}
I have the same problem before, instead of passing db to routing function, My solution is to make db variable global like
var mongojs = require('mongojs')
global.db = mongojs(<mongodb url>);
then db variable can be used in any part of your code
If you're using express, put that in your app.js file and you will never have to worry about db variable anyore.
PS: some people think that using global is not a good practices, but I argue that since global is a node.js features and especially since it works, why not
node.js global variables?
You don't have tell the codes, that which database you want to use.
how to get databases list https://stackoverflow.com/a/71895254/17576982
here is the sample code to find the movie with name 'Back to the Future' in database sample_mflix > collection movies:
const { MongoClient } = require("mongodb");
// Replace the uri string with your MongoDB deployment's connection string.
const uri =
"mongodb+srv://<user>:<password>#<cluster-url>?retryWrites=true&writeConcern=majority";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// Query for a movie that has the title 'Back to the Future'
const query = { title: 'Back to the Future' };
const movie = await movies.findOne(query);
console.log(movie);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
to get list of database, put await client.db().admin().listDatabases() on fun function. e.g.
async function run() {
try {
await client.connect();
var databasesList = await client.db().admin().listDatabases();
console.log("Databases:");
databasesList.databases.forEach(db => console.log(` - ${db.name}`));
learn MongoDB more from official docs: https://www.mongodb.com/docs

Grunt task not calling external javascript task

I am trying to insert data to mongodb using a grunt task. Init.js is the file which is located in "tasks" directory. So, i registered the task as:
grunt.registerTask('dbinit', function () {
grunt.task.loadTasks('tasks');
}
tasks directory has Init.js:
var mongoose = require('mongoose'),
config = require('/lib/config/config.js'),
mongoose = require('mongoose'),
dbmodel = require('/lib/models/user.js'),
db;
mongoose.connect(config.mongo.uri, config.mongo.options);
db = mongoose.connection;
db.on('open', function () {
var user = new dbmodel.User({
userId : 'bond007'
});
console.log('Adding seed user: '+user);
newUser.save(function (err, product, numberAffected) {
if (err) {
console.log(err);
} else {
console.log("saved user: "+user.userId);
}
db.close();
});
});
The problem is that Init.js is never called. I am not sure if it is an async issue or issue with calling Init.js but I see the "dbinit" task "Done without errors".
Grunt tasks by default execute synchronously, the task will finish and not wait for the mongoose connection to open. Use this.async() within the task to have the task wait.
A better strategy might be to wrap parts within tasks/Init.js in a task like such:
var mongoose = require('mongoose'),
config = require('/lib/config/config.js'),
mongoose = require('mongoose'),
dbmodel = require('/lib/models/user.js'),
db;
grunt.registerTask('dbinit', function() {
var done = this.async();
mongoose.connect(config.mongo.uri, config.mongo.options);
db = mongoose.connection;
db.on('open', function () {
var user = new dbmodel.User({
userId : 'bond007'
});
console.log('Adding seed user: '+user);
newUser.save(function (err, product, numberAffected) {
if (err) {
console.log(err);
} else {
console.log("saved user: "+user.userId);
}
db.close();
done(); // Call done to close the task
});
});
});
Then just use grunt.loadTasks('tasks'); in your gruntfile.

Node.js: how to load modules without executing them?

I have a simple file model.js like follows:
var mongo = require('mongodb');
var mongoUri = process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/mydb';
exports.connect = mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
and in my web.js I load the model using model = require('./model.js'). One werid thing is that although I did not call model.connect(), the message "Connect to the database successfully" still got logged to my console. Why is this happening and is there a way to avoid it?
EDIT:Never mind I have found a workaround:
exports.connect = function(){
mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
}
exports.connect = mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
You just called mongo.Db.connect() and assigned its result to exports.connect.
That code runs as soon as you require() the module.
Instead, you need to create a function:
exports.connect = function() { ... };

Node.js Mongoose nothing happens

I am trying to connect to my mongodb database, but it doesn't work : it doesn't run the callback, and no error is thrown :
var config = require('./config');
var mongoose = require('mongoose');
var schemas = require('./app/schemas');
var model = require('./app/model');
mongoose.connect(config.db_connection, function (err) {
if (err) {
throw err;
}
});
var ModModel = mongoose.model('mods', schemas.modScheme);
var query = ModModel.find();
query.exec('find', function (err, mods) {
if (err) {
throw err;
}
console.log('Retriveing mods...');
console.log(mods);
});
EDIT : This new code don't work
Here is the whole code : https://github.com/CraftYourModCorporation/RedstoneHub
(May not be complete, route getmods)
Could someone link a project that uses mongoose please ?
And output :
Important: use 'process.env.PORT' as the port and 'process.env.IP' as the host in your scripts!
debugger listening on port 15400
Process terminated
Thanks all of you, The problem was the connection string : instead of connecting using mongodb://user:pass#host/db, i had to use options. More details here : http://mongoosejs.com/docs/connections.html

Categories

Resources