Cannot read property of 'insert' of underfined mongoDB NodeJS - javascript

I am trying to incorporate mongoDB into my application, however when I try to add to a collection I get the error 'cannot read property of 'insert' undefined when trying to start the server with nodeJS.
I appreciate that this has been asked before, however when I have tried to rectify the error as per another question asked on here by writing the following code, however I get var is not defined;
var accountCollection = var mongodb = mongodb.collection('account');
accountCollection.insert({username:"wendy3", password:"lilac3"});
The relevant code for my server is below, I have looked at many guides online and nothing seems to solve my problem, so any help would be appreciated.
//create server, listening on port 3000
//when there is a request to port 3000 the server is notified
//depending on the request a specific action will be carried out
var mongodb = require("mongodb");
//create connection to MongoDB
var db = mongodb('localhost:27017/Game', ['account', 'progress']);
//insert into collection
db.account.insert({username:"wendy3", password:"lilac3"});
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var colors = require('colors/safe');

Connection to a database is an asynchronous operation but you're trying to access it as if it was synchronous.
If you look at the examples for the package you're using, it shows that you must you use a callback function which gets called once the connection response is received:
var MongoClient = require('mongodb').MongoClient;
// Connection URL
var url = 'localhost:27017/Game';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
if (err) return console.log('Error: ' + err);
console.log("Connected correctly to server");
});

Thank you - I think I understand now ( I am new to MongoDB so please forgive me)
I now have the following code; however I am receiving error invalid schema, expected mongodb. Have I maybe put MongoClient in place of mongodb somewhere? So I can see that it is trying to connect, however the callback is returning an error.
Code:
var MongoClient = require('mongodb').MongoClient;
//connection url
var url = ('localhost:27017/Game', 'account', 'progress');
//use connect method to connect to server
MongoClient.connect(url, function(err, db){
if (err) return console.log('Error: ' + err);
console.log('mongodb is connected to the server');
});

Related

Close SQL connection Nodejs

I tried to close the connection for the below query by using connection.close(). but it is not working, so how to close connection inside route file
var express = require('express');
var router = express.Router();
var connection = require('../database.js');
var db = require('../database.js');
/* GET home page. */
router.get('/', function(req, res, next) {
connection.query("Select users..... ",function(err,supervisorrows) {
if(err){
req.flash('error', err);
res.render('View',{page_title:"Users - Node.js",supervisor:''});
}else{
res.render('View',{page_title:"Users - Node.js",supervisor:supervisorrows.recordset});
}
});
module.exports = router;
According to mysql npm docs There are two ways to end a connection :
connection.end() method
connection.destroy() method
The first one will make sure all previously enqueued queries are still before sending a COM_QUIT packet to the MySQL server.
The second one terminates a connection immediately and guarantees that no more events or callbacks will be triggered for the connection.

How to get JSON data from node.js to HTML

I am trying to create a web app with some drop down menus that contain data from a sql server database. After some searching I figured out how to use node.js to output the table data into the command prompt.
var sql = require('mssql/msnodesqlv8');
var config = {
connectionString: 'Driver=SQL Server;Server=NAME\\SQLEXPRESS;Database=master;Trusted_Connection=true;'
};
sql.connect(config, err => {
new sql.Request().query('SELECT * FROM TABLE', (err, result) => {
console.log("Works");
if(err) { // SQL error, but connection OK.
console.log(" Error: "+ err);
} else { // All good.
console.dir(result);
};
});
});
sql.on('error', err => { // Connection bad.
console.log("Bad");
console.log(" Error: "+ err);
});
Now the problem is I don't know how to get that result into JSON data that can be used in my web app. Any help would be appreciated as I am quite new to node.js. Thanks!
EDIT:
Thanks for the help so far! I added the following code for when there is no error:
var express = require('express')
var app = express()
JSON.stringify(result);
console.log(JSON.stringify(result));
app.get('/', function (req, res) {
res.send(result)
})
I also have all of the code for the http server but I don't think it's necessary to show it all. Is this all that is needed on the server side?
First of all, to send data from the server to the client you'll have to run an HTTP server as part of your Node backend. Then, once the web app loads, it should make a request to your server, which as a response will return the data from the database. For more information on how to do this check out Express (for the server side) and Fetch API (for the client side).

confusion about how connection.end() works in node.js mySQL module

const mysql = require('mysql');
let connection = mysql.createConnection(...);
connection.connect((err)=>{
...
connection.query((err)=>{
...
connection.end();});
});
After I close the connection by using
connection.end()
, if I want to query the database again using the same credentials, do I need to make a new connection by calling
mysql.createConnection(...)
Or can I reuse the same connection by simply calling
connection.connect(...)
A little background: I'm deploying an angular/node.js app to a shared hosting website, and the web host has a maximum limit of 25 concurrent connections to mySQL database, therefore I need to make sure I close a connection properly after a user does his query. I am not sure if I could reuse the connection created by mysql.createConnection(...) after I close that connection, or do I need to create a brand new connection.
You can use one global connection for getting data from db .
If You working on single file than you can write as
app.js one file only
var mysql = require('mysql');
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function (error, results, fields) {
if (error) throw error;
// connected!
});
if you want to use same connection in multiple file than you can write as
app.js
app.use(
connection(mysql, {
host: xxxxx,
user: 'root',
password : xxxx,
port : 3306,
database:dbname
},'pool'),
);
var oem = require('./routes/type');
app.get('/api/oemtype',oem.type);
For the second file
type.js
exports.type = function(req, res){
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM type',function(err,rows)
{
if(err)
res.json({
status:0
});
res.send(rows);
res.render('customers',{page_title:"Customers - Node.js",data:rows});
});
});
};
No need to use of connection.end().

Express.js Not letting me handle errors: Exception has occurred: Error _runMicrotasks();

So I'm querying the Blizzard API Battle.Net for some information, character name and the realm they're in. Ofcourse it's possible for a user to query for a character that Does Not Exist, so Blizzard throws a 404 back to me and my server.js file doesn't know what to do with it even though I put something in place to handle it.
Releveant server.js code:
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
const blizzard = require('blizzard.js').initialize({apikey: "dummy"});
app.use(express.static(__dirname + '/Source'));
//Listen on port 3000
app.listen(3000, function() {
console.log("Launch successful. To access app, open your browser and insert the following URL into your address bar: http://localhost:3000/");
});
app.post('/buttonpress', jsonParser, function (req, res) {
blizzard.wow.character(['profile'], { origin: 'us', realm: req.body.realm.name, name: req.body.name })
.then(response => {
if(response.status != 200){
res.send("That character doesn't exist! Please enter a valid character name.");
} else {
console.log(response.data);
res.send(response.data);
}
});
});
I attempt to handle anything that's not a 200 by sending something to the client to tell the user: Character DNE!, but instead vscode gives me some red error codes mentioned in the title of this post (in vscode debugger anyway).
When I try this from a command line, just running node server.js, nothing happens when I click the Search Button. I've set breakpoints and it looks like the function doesn't get a response from the server. So the 404 is happening no matter what but I can't figure out how to handle it.
Try placing your app.listen below/after your app.post Express.js runs in a middleware functionality so your listen is blocking all preceding code.

Using app.get inside the function connecting DB - NodeJs

I am using NodeJs along with MySQL. I am using node-mysql after looking at MySQL with Node.js. Now the problem is I am trying to make db connection only once and using GETs inside it but it's not working.
Code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function(err) {
// connected! (unless `err` is set)
app.get('/hello',function(req,res){
console.log('Hello');
res.send('Hi');
});
});
But the above code is not working. It is not recognizing the route. But making a connection inside every get function works.
I should be doing something wrong. Is there any way such that I can connect to the Db only once ?
You should move your call to app.get to the top level scope of the file. These calls are declarative and should be thought of more like configuring your application than the application's business logic. From the mysql docs, the connection object will automatically implicitly open a connection to the database if connection.query is called and a connection is not yet established. That sounds like the mechanism you should take advantage of.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
app.get('/hello',function(req,res){
console.log('Hello');
connection.query('select * from users', function (error, result) {
res.send('Hi');
});
});

Categories

Resources