Inserting multiple rows dynamically in mysql database node js? - javascript

I am trying to insert multiple rows in mysql database using node js.The idea is that I have four arrays which has 20 values each. My goal is to dynamically insert all the values in my database using node js. Now, I am a bit confused how I should go about it.
This is my server file-
server.js -
const express = require('express');
const app = express();
var db = require("./DatabaseConfig.js");
var cookieParser = require('cookie-parser');
var path = require('path');
var bodyParser = require('body-parser');
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
res.send('Hello World!')
});
app.listen(4000, function () {
console.log('Example app listening on port 4000!')
});
app.get("/home",function(req,res){
res.render("Home.ejs");
});
app.post("/home",function(req,res)
{
var data = JSON.parse(req.body.info);
console.log(data.length);
var counter = [];
var publicationtitle=[];
var publicationdate =[];
var publicationlink=[];
for(var i=0;i<data.length;i++)
{
counter.push(0);
publicationtitle.push(data[i]["title"]);
publicationdate.push(data[i]["pubDate"]);
publicationlink.push(data[i]["link"]);
}
var res = db.dbconfig();
var values = [
publicationtitle, publicationlink,publicationdate,counter
];
console.log("values",values);
db.insertrecord(values);
values=[];
});
DatabaseConfig.js
var mysql = require('mysql');
var con = mysql.createConnection({
host : 'localhost',
user : '****',
password : '****',
database : 'test',
multipleStatements: true
});
var values = [];
module.exports = {
dbconfig: function(error) {
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
},
insertrecord:function(values){
var sql = "INSERT INTO rsscontent (title,link,date,count) VALUES ?";
con.query(sql,[values], function(err) {
if (err) throw err;
con.end();
});
}
};
Any suggestions or advise will be highly appreciated.

You can build your query and values like this:
let placeholder = users.map(() => "(?, ?)").join(",");
let query =
`INSERT INTO ${TABLE_NAME.USER}
(id, username)
VALUES ${placeholder}`;
let values = [];
users.forEach(user => {
values.push(user.id);
values.push(user.username);
});
Been using this and it worked fine.

Other than what have been answered, your INSERT statement is bound to throw error since date is a keyword and should be escaped like
var sql = "INSERT INTO rsscontent (title,link,`date`,count) VALUES ?";

Related

How to get values from mongodb and display in HTML

I am new to mongodb, I am using Express, Body-Parser and Mongoose and I have a mongodb database (its online, its call mlab) where i pull data from. Every thing is working fine, i have used postman to Get, Post and Delete. I am trying to get the data in JavaScript so i can display in the html. I am using Ajax, it works and returns success, but fires the fail function of the Ajax.
exports.photoalbum_all = function (req, res, next) {
PhotoAlbum.find(({}), function (err, photoalbum) {
if (err) return next(err);
res.send("../Views/images", {photo: photoalbum});
});
};
The mongodb model
const mongoose = require('mongoose');
const Schema = mongoose.Schema,
let PhotoAlbumSchema = new Schema({
title: String,
albums:[
{
u_name: String,
u_title: String
}]
},{
timestamps: true
});
PhotoAlbumSchema.virtual('pictureId').get(function(){
return this._id;
});
The mongodb route
const express = require('express');
const router = express.Router();
//
// Require the controllers
const photoalbum_controller =
require('../controllers/photoalbum.controller');
//
router.get('/find', photoalbum_controller.photoalbum_all);
The app.js
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const photoalbum = require('./routes/photoalbum.route'); // Imports routes for the photos
//
const app = express();
//
// Set up mongoose connection
const mongoose = require('mongoose');
let dev_db_url = 'mongodb://Trex_son:Salvat1on1987#ds243254.mlab.com:43254/photoalbumdb';
let mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(mongoDB, { useNewUrlParser: true });
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/photoalbums', photoalbum);
let port = 1234;
app.listen(port, () => {
console.log('Server is up and running on port number ' + port);
});
I'm not sure Ajax is the best way to retrieve this data, is there any better to retrieve this values to the html

Using variables through scripts using module.exports not working

So im pulling my hair here and everything I've tried hasn't worked. I have a simple node.js app structure, like this:
var express = require('express');
var path = require('path');
var mysql = require('mysql');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
//Database handler
//Here is completed with the data
var con = mysql.createConnection({
host: "",
user: "",
password: "",
database: ""
});
con.connect(function (err) {
if(err) throw err;
console.log("connected");
});
app.listen(55132, function () {
console.log("Server running at port 55132");
});
module.exports = app;
Quite simple, some routing but nothing weird. I need to use the variable con in my other scripts, so i've tried this:
module.exports.database = con;
So i should be able to use it in my index.js script (see var indexRouter), soooo here is the index.js script:
var express = require('express');
var router = express.Router();
let app = require('../app');
let connection = app.database;
console.log(app); //Here returns {} so I canĀ“t access any of the properties of the module
/* GET home page. */
router.get('/', function(req, res, next) {
}
module.exports = router;
I don't know what should I do, some suggestion?
for forther reading i recommend you to read this
https://nodejs.org/api/modules.html#modules_exports_shortcut
just change you app file export to
module.exports = {app,con};
and in your index file
const {app,con} = require('./app');
let connection = con;
You can you try with
for and example :
var function = function(coid, userid, callback) {}
exports.function = function ;
in your case
exports.database = con;
Now it should work, you won't need to add module in the above.

NodeJS server returning empty data from MongoDB

I am making an app where the app is going to send the POST request data to the nodeJS server. The JSON format of the content looks like: {"encrypteddata": "someencryptedvalueofthetext"}. This data will be saved in a MongoDB.
I created two file one is app.js and another is /models/encdata.js. Content of both the file is given below.
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.use(bodyParser.json());
ENCDATA = require('./models/encdata');
mongoose.connect('mongodb://localhost/encdata', { useMongoClient: true }); // the url access the database
var db = mongoose.connection;
app.get('/', function(req, res){
res.send('Visit /api/encdata');
app.get('/api/encdata', function(req, res){
ENCDATA.getENCDATA(function(err, encdata){
if(err){
throw err;
}
res.json(encdata);
});
});
app.post('/api/encdata', function(req, res){
var encdata = req.body;
ENCDATA.addENCDATA(encdata, function(err, encdata){
if(err){
throw err;
}
res.json(encdata);
});
});
});
app.listen(3000);
console.log('Running on port 3000');
encdata.js
var mongoose = require('mongoose');
var encdataencryptSchema = mongoose.Schema({
encrypteddata: {
type: String,
required: true
}
});
var ENCDATA = module.exports = mongoose.model('encdata', encdataencryptSchema);
module.exports.getENCDATA = function(callback, limit){
ENCDATA.find(callback).limit(limit);
}
module.exports.addENCDATA = function(encdata, callback){
ENCDATA.create(encdata, callback);
}
And data in MongoDB is:
{"encrypteddata": "someencryptedvalueofthetext"}
But when I make a GET request to the url localhost:3000/api/encdata it shows [] (an empty array although I have data). Even the POST request is not working and I am not able to save any data.
I rewrote your code by changing the name of the variable and it worked for me. The app.js file looks something like this:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var http = require('http');
app.use(bodyParser.json());
AES = require('./models/aes');
mongoose.connect('mongodb://localhost/aes', { useMongoClient: true }); // the url access the database
var db = mongoose.connection;
app.get('/', function(req, res){
res.send('Visit /api/aes');
app.get('/api/aes', function(req, res){
AES.getAES(function(err, aes){
if(err){
throw err;
}
res.json(aes);
});
});
app.post('/api/aes', function(req, res){
var aes = req.body;
AES.addAES(aes, function(err, aes){
if(err){
throw err;
}
res.json(aes);
});
});
});
app.listen(3000);
console.log('Running on port 3000');
In the encdata.js you can change the variable to AES. Name the mongodb collection and database as aes.

issue with angular 4 and nodejs , serve index.html based on URL like /admin and /

Hi i have setup three project api(nodejs) , admin(angular 4) and website(angular 4) , after build i got two UI folder admin-dist and web-dist , I want to access these app based on URL '/admin' will access admin-dist and '/' will access web-dist , I have placed these two folder on of api folder
For accessing these app i have written node code like this ,But i am not able to access ,
Please help me, Thanks in advance ..
app.js
var express = require('express');
router = express.Router();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cookieParser = require('cookie-parser');
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')
var cors = require('cors');
var User = require('./models/user.model');
var dbConfig = require('./config/db');
var app = express();
app.use(cors());
app.use(cookieParser());
// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'});
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}));
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, function (err) {
if (err) {
console.log('faild to connect with mongo DB', err);
}
else {
console.log('Connection open with mongo db');
}
})
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', router);
var userRoute = require('./routes/user.route')(router);
// var profileRoute = require('./routes/profile.route')(app);
// var productRoute=require('./routes/products.route')(app);
app.use(express.static(__dirname + '/admin-dist'));
app.get('/admin', function (req, res) {
console.log('admin route');
return res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.get('/admin/*', function (req, res) {
res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.use(express.static(__dirname + '/front-dist'));
app.get('/', function (req, res) {
console.log('web route');
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.use('/*',function(req, res) {
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.listen(port, function (err) {
if (err) {
console.log(err);
}
else {
console.log('Server api runing on port ', port);
}
})

How to query using MySQL in an EJS File

I am trying to run a query in a view (.ejs file). However, since the keyword require is not defined in a .ejs file, I need to export it from my main file, server.js.
The whole code for my server.js file is below and this is the specific snippet with which I need help.
app.engine('html', require('ejs').renderFile);
exports.profile = function(req, res) {
res.render('profile', { mysql: mysql });
}
I need to be able to use the mysql.createConnection in my profile.ejs file.
Any help would be great.
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
var Connection = require('tedious').Connection;
var config = {
userName: 'DESKTOP-S6CM9A9\\Yash',
password: '',
server: 'DESKTOP-S6CM9A9\\SQLEXPRESS',
};
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "yashm"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql="Select * from test.productlist";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
app.engine('html', require('ejs').renderFile);
exports.profile = function(req, res) {
res.render('profile', { mysql: mysql });
}
//--------------------------------------------------------------------------------
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: 'test run' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
Like already said in the comment, you have to do your query logic in your server.js and then pass the data to your view (or maybe even pre-process it!)
exports.profile = function(req, res) {
con.query('SELECT 1', function (error, results, fields) {
if (error) throw error;
// connected!
res.render('profile', { data: results });
});
}
In your ejs you can loop trough the data, and acces the fields as data[i]['fieldname']
<ul>
<% for(var i=0; i<data.length; i++) {%>
<li><%= data[i]['id'] %></li>
<% } %>
</ul>

Categories

Resources