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

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".

Related

Read SQLite database with Node.js

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.');
});

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).

Pass values from Server to Client | Node to Angular

I'm very new to MEAN. I'm trying to send a dataset from Node to my Angular Controller. However, the angular controller isn't receiving the correct information and is resulting in null.
My view is called booklist.jade
Here is my server side (Node JS)
router.get('/thelist', function(req, res){
res.render('booklist');
});
router.get('/thelist/data', function(req, res){
.
.
.
// Find all books
collection.find({}).toArray(function (err, result) {
if (err) {
res.send(err);
} else if (result.length) {
res.json({booklist : result});
} else {
res.send('No documents found');
}
//Close connection
db.close();
});
}
});
});
Here is my client side (Angular JS)
function booksController($scope)
{
$http.get("http://localhost:3000/thelist/data").success(function( data ) {
$scope.book=10; //THIS WORKS
$scope.table= data;
});
}
Basically, I want $scope.table to have all data from my server. Any ideas on why this is failing?
UPDATE: On trying some console log checks, I found out that the request router.get('/thelist/data', function(req, res) isn't being called by the Angular Controller.
res.json({booklist : result});
as per your code you are sending result in booklist attribute
Hence while reading you should say $scope.table= data.booklist;
My client side controller was wrong. Here is the correct one.
app.controller('booksController',['$scope','$http',
function($scope,$http) {
$http.get("http://localhost:3000/thelist/data").success(function( data ) {
$scope.book=data;
});
}]);

Fetching data from mongodb through nodejs and express to a html page

Basically, I want to show particular fields from "employees" collection into a html page. But even after searching a lot on web, I'm unable to do so.
Here is the route part from the server.js file:
app.get('/fetching', function(req, res){
connection.fetcher(function(data)
{
res.render("testing.html",data);
}
);
});
Now this is the part from connection.js file:
var fetcher= function(callback) {
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('employees');
collection.find({},function (err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
callback(result);
}
});
}
});
Now, findOne is working fine and returning the value to server.js file perfectly. But I need to use "find", so how to send the complete array to the server.js through callback?
And moreover, I need to send that retrieved data from server.js to a HTML file called testing.html through rendering and display it through angular js. Please explain a simple way to do so.
EDIT:
I got to know how to work with "find", I just used "toArray" alongwith "find" in function. And now, I'm able to return the value to server.js through call back. But the other question is still unsolved: How do I pass those values to the html page?
Using ejs, you need to set the view engine:
app.set('view engine', 'ejs');
Then get your data:
app.get('/employees',(req , res) =>{
db.collection('employees').find().toArray(function(err , i){
if (err) return console.log(err)
res.render('index.ejs',{employees: i})
})
});
The .ejs file would be like this:
employees
<ul class="employees">
<% for(var i=0; i<employees.length; i++) {%>
<li class="employees">
<span><%= " Nome: " +employees[i].name+"."%></span>
<span><%=" Address: " + employees[i].address%></span>
</li>
<% } %>
</ul>
Just a simple way using ejs. Hope it helps to clarify things.

How to use node-mysql correctly with Express.js?

I'm wondering how to use the module node-mysql correctly in Node.js (using Express.js). I have a main router with this:
var Post = require('./models/post.js');
app.get('/archives', function (req, res) {
Post.findArchives(function(posts, err) {
if(err)
res.send('404 Not found', 404);
else
res.render('archives', { posts: posts});
});
});
And here's the content of the file post.js:
var mysql = require('mysql');
var dbURL = 'mysql://root#localhost/mydatabase';
exports.findArchives = function(callback) {
var connection = mysql.createConnection(dbURL);
connection.query('SELECT * FROM blog_posts_view WHERE status != 0 ORDER BY date DESC', function(err, rows) {
if(err) throw err
callback(rows, err);
connection.end();
});
};
How can I improve it? Improve the error handling? Also, there's the function handleDisconnect(connection); on their Github (https://github.com/felixge/node-mysql) that I'm not really sure how to integrate to make sure that the application will not crash when the database is not responding.
Thanks!
Take a look at the mysql-simple library. It combines node-mysql with a pooling library to create a connection pool, and also includes the code to handle the disconnects.
If you want to make it super easy, you could just use that module.

Categories