Read SQLite database with Node.js - javascript

Having this SQLite DB I'm trying to read the data from it. So, from table Athlete I want to read the first 3 columns.
This is the code (app.js):
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('ocs_athletes');
db.serialize(function () {
db.each('SELECT athlete_id, name, surname FROM Athlete', function (err, row) {
console.log('User: ', row.athlete_id, row.name, row.surname);
});
});
db.close();
The file app.js is in the same folder as the db file - ocs_athletes.
Running in cmd node app.js returns this error message:
/home/dd/Documents/Projects/OCSapp/app.js:6
console.log('User: ', row.athlete_id, row.name, row.surname);
^
TypeError: Cannot read property 'athlete_id' of undefined
at /home/dd/Documents/Projects/OCSapp/app.js:6:31
at replacement (/home/dd/Documents/Projects/OCSapp/node_modules/sqlite3/lib/trace.js:25:27)
at Statement.errBack (/home/dd/Documents/Projects/OCSapp/node_modules/sqlite3/lib/sqlite3.js:14:21)
Why is this happening?

Try connecting to db like this.
let db = new sqlite3.Database('./ocs_athlete.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the my database.');
});
Give path of .db file. This will work.
There are three opening modes:
sqlite3.OPEN_READONLY: open the database for read-only.
sqlite3.OPEN_READWRITE : open the database for reading and writting.
sqlite3.OPEN_CREATE: open the database, if the database does not exist, create a new database.
To open the chinook sample database for read and write, you can do it as follows:
let db = new sqlite3.Database('./ocs_athlete.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the ocs_athlete database.');
});

Related

Failing to connect to MongoDB hosted on mlab

Background
Making a small web app that connects to a Mongo DB hosted with Mlab. I've created the DB on mlab, and created users with read/write permission. I've also created a users collection with several records.
The Problem
When I try and connect to the database using the code on mongo.github.io, I hit the error:
/home/ed/dev/mongo-demo/node_modules/mongodb/lib/operations/mongo_client_ops.js:466
throw err;
^
TypeError: Cannot read property 'db' of null
The Code
var MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://<user>:<pass>#ds115434.mlab.com:15434';
// Database Name
const dbName = 'princee3-music';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
What I Have Tried
Oddly, if I connect through the shell using:
mongo ds115434.mlab.com:15434/princee3-music -u <dbuser> -p <dbpassword>
That works fine, or if I wrap the connection in an anonymous self-calling async function, it also connects.
Async Wrapper
const MongoClient = require('mongodb').MongoClient;
const mongoUrl = 'mongodb://<user>:<pass>#ds115434.mlab.com:15434/';
const dbName = 'princee3-music';
(async() => {
const client = await MongoClient.connect(mongoUrl, { useNewUrlParser: true});
const db = client.db(dbName);
db.collection('users').insertOne({
email: user.email,
pass: hashedPassword,
admin: true
}, (err, result) => {
if (err) {
reject({error: err});
} else {
resolve({message: 'okay'});
}
});
client.close();
})();
Any pointers on where I may be going wrong would be great.
The official mLab docs advise to connect like below. It has to be asynchronous , in order to wait for the connection to occur, or the client will be null, thus throwing an error saying that it can’t read property db of null.
On the other hand, you async has useNewUrlParser which might be the key to have a successful connection, see this issue
MongoClient.connect(url, { useNewUrlParser: true }).then(client => client.db())

mongo database doesn't show up in command line

I don't understand why my mongo db isn't showing up when I run "show databases" in the command line. I see other mongo db's I created in the past, but not the current one. Here is my code: (using mongoose ORM):
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/fuelTracker');
var Schema = mongoose.Schema;
var fuelSchema = new Schema({
time : { type : Date, default: Date.now },
miles : Number,
gallons: Number
});
var FuelStop = mongoose.model('FuelStop', fuelSchema);
module.exports = FuelStop;
And where I'm attempting a basic model.save operation:
app.post('/', function (req, res ) {
results = req.body;
var fuelStop = new FuelStop (results)
fuelStop.save(function() {
console.log('record saved to monogoDB');
});
})
Any clue as to why my 'fuelTracker' database doesn't appear in the command line when I run 'show databases' within mongo?
THANK YOU!!
did you try show dbs? show databases print all databases available, see the doc here: https://docs.mongodb.com/manual/reference/mongo-shell/
The database doesn't get created until you insert data into a collection in the database.
I tested your code by creating and running a script to seed the fuelTracker database with example JSON data. I then ran show databases and was able to see fuelTracker listed.
If you would like to try this, in a new file seed.js:
const db = require('./fileName.js');
const fs = require('fs');
let fuelData = fs.readFileSync('./data.json', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
let jsonFuel = JSON.parse(fuelData);
db.remove({}, () => {
console.log('Successfully removed fuel data');
db.collection.insert(jsonFuel, (err, docs) => {
if (err) {
console.log(`error inserting data: ${err}`);
} else {
console.log(`Fuel data was stored: ${docs}`);
}
});
});
Then create example data in data.json:
[
{
"time":"04/18/2018",
"miles":"28",
"gallons":"30"
}
]
Then run your seed file and your database should hopefully be showing up.

Missing argument list bracket error

app.get("/editMBTI", editMBTIFunc(req, res)
{
// making MongoClient available to all the EJS Files
// app.locals.MongoClient= MongoClient;
MongoClient.connect(url, function (err, client) {
assert.equal(null, err);
console.log("Connected Successfully to the Database server");
const db = client.db(dbName);
//getting the whole collection of MBTI sets
var cursor = db.collection("mbti_testcontent").find();
cursor.each(function (err, doc) {
console.log(doc);
//send the above retrieved doc to the editMBTI.ejs file(front- end)
res.render('editMBTI', {
'mbti_content': doc,
'db_url': url,
'dbName': dbName
});
});
});
});
The above is the code and the image of the terminal(https://i.stack.imgur.com/XcOti.png). Why is the missing argument bracket error poping up in the editMBTI api ? I have closed all the brackets that were opened. Where is it missing ?
Change this line:
app.get("/editMBTI", editMBTIFunc(req, res)
to this:
app.get("/editMBTI", function editMBTIFunc(req, res)
FYI, a tool like JSHint or JSLint will often give you more detailed info about where something is wrong (which is what I used to see this more easily).

MongoDB&NodeJS: How to display a certain field on a Jade file on a server

So I just started learning MEAN and I want to show only a certain field of a database I've made to a Node server. I'm using Express as well. Here is my code so far.
index.js
router.get('/generate', function(req, res) {
// get out mongoclient to work with our mongo server
var MongoClient = mongodb.MongoClient;
// where the mongodb server is
var url = 'mongodb://localhost:27017/data';
MongoClient.connect(url, function(err, db) {
if(err) {
console.log('Unable to connect to server', err);
} else {
console.log('Connection established');
var collection = db.collection('compliments');
collection.find({}).toArray(function(err, result) {
if (err) {
res.send(err);
} else if (result.length) {
res.json(result); // problem here
} else {
res.send('No documents found');
}
db.close();
});
}
});
});
generate.jade
doctype html
html
head
title("Compliment Generator")
body
h1 !{title}
block content
h3.
!{compliment}
This is what it looks like on localhost:3000/generate
[{"_id":"570b50f8265f2536d2fd6ed6","type":"compliment","content":"You are absolutely gorgeous."},{"_id":"570b50f8265f2536d2fd6ed7","type":"compliment","content":"You are wonderful."},{"_id":"570b50f8265f2536d2fd6ed8","type":"compliment","content":"I could look at you all day."}]
How do I make it so that it only displays the "content"? Thanks!
If I understand correctly you only want the content to be returned from the query.
The below link should be of use:
https://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/
You essentially want to modify the query to only retrieve the "Content" part like so:
collection.find({}, { content: 1, _id:0 })
This will specify that you don't want to include the "_id" (which is included by default) and you do want to include the "content".

Node.js app giving ERR_EMPTY_RESPONSE

I'm having serious issues with an app I am building with Node.js, Express, MongoDB and Mongoose. Last night everything seemed to work when I used nodemon server.js to `run the server. On the command line everything seems to be working but on the browser (in particular Chrome) I get the following error: No data received ERR_EMPTY_RESPONSE. I've tried other Node projects on my machine and they too are struggling to work. I did a npm update last night in order to update my modules because of another error I was getting from MongoDB/Mongoose { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND'}. I used the solution in this answer to try and fix it and it didn't work and I still get that error. Now I don't get any files at all being served to my browser. My code is below. Please help:
//grab express and Mongoose
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create an express app
var app = express();
app.use(express.static('/public/css', {"root": __dirname}));
//create a database
mongoose.connect('mongodb://localhost/__dirname');
//connect to the data store on the set up the database
var db = mongoose.connection;
//Create a model which connects to the schema and entries collection in the __dirname database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");
mongoose.connection.on("open", function() {
console.log("mongodb is connected!");
});
//start the server on the port 8080
app.listen(8080);
//The routes
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
//create an express route for the home page at http://localhost:8080/
app.get('/', function(req, res) {
res.send('ok');
res.sendFile('/views/index.html', {"root": __dirname + ''});
});
//Send a message to the console
console.log('The server has started');
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
These routes don't send anything back to the client via res. The bson error isn't a big deal - it's just telling you it can't use the C++ bson parser and instead is using the native JS one.
A fix could be:
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {
if (err) {
res.status(404).json({"error":"not found","err":err});
return;
}
res.json(data);
});
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
res.status(500).json({ error: "save failed", err: err});
return;
} else {
res.status(201).json(newMonth);
};
});
});
updated june 2020
ERR_EMPTY_RESPONSE express js
package.json
"cors": "^2.8.4",
"csurf": "^1.9.0",
"express": "^4.15.4",
this error show when you try to access with the wrong HTTP request. check first your request was correct
maybe your cors parameter wrong

Categories