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.
Related
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".
I have watched and read loads of tutorials now on node.js and mongodb. I know how to create databases, Insert data, show that data on a ejs file, etc etc. However, I have no idea how to insert data from that ejs file.
For example:
I have an app.js and a mongodb.js the app runs my server and the mongodb.js creates a database and inserts some data - not with mongoose but rather with mongodb. I also have a few ejs files that get the data from mongodb.js and displays it. Heres my mongodb.js:
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/my_database_name';
exports.drinks = [
{ name: 'Manu', rate: 3 },
{ name: 'Martin', rate: 5 },
{ name: 'Bob', rate: 10 }
];
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('users');
// Insert some users
collection.insert(exports.drinks, function (err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
}
console.log(collection.users.find());
//Close connection
db.close();
});
}
});
Then in my app.js I have this:
//index page
app.get('/', function(req, res) {
res.render('pages/index', {
drinks: drinks,
tagline: tagline
});
});
And on my ejs:
<ul>
<% drinks.forEach(function(drink) { %>
<li><%= drink.name %> : <%= drink.rate %></li>
<% });; %>
</ul>
But now I want to be able to update/insert data into my database from my ejs (or even from my app.js).
For example if I have a form and I want the user to type their name inside I want that to be saved in my db. How do I do this?
Ejs only template engine (View in MVC), It cant update and insert database (Controller do this). You need make a route (POST) for get user data and update to database.
What does res.render do, and what does the html file look like?
My end goal is to load arbitrary comma-separated-values from a text file into an html file (for example). I was only able to deduce that a view was the html file, and callback gives that html file back.
Here is the documentation: http://expressjs.com/api.html#res.render.
Now, given context from some example code I found, there is something about using ejs (embedded javascript) with <% and %>.
But if I may add, am I just incompetent or is the documentation really truly vague and assumes the reader knows everything? How could I have gone about figuring this out on my own? Is there any official documentation so I can gain a full understanding of usage, advantages and pitfalls?
Edit 1
I just want to add that I'm having a heck of a time learning node.js.
Is it me or is the general documentation really vague? Aside from lousy explanations like above, there are no type specifications for parameters or return values.
Edit 2
Let me ask you some more specific questions above the code.
The actual orders.ejs file is in views/orders.ejs. How does this code refer to it?
HTML excerpt:
<tbody>
<% for(var i=0; i<orders.length; i++) {%>
<tr>
<td><%= orders[i].id %></td>
<td><%= orders[i].amount %></td>
<td><%= orders[i].time %></td>
</tr>
<% } %>
And the js. Please see /orders:
// Define routes for simple SSJS web app.
// Writes Coinbase orders to database.
var async = require('async')
, express = require('express')
, fs = require('fs')
, http = require('http')
, https = require('https')
, db = require('./models');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('port', process.env.PORT || 8080);
// Render homepage (note trailing slash): example.com/
app.get('/', function(request, response) {
var data = fs.readFileSync('index.html').toString();
response.send(data);
});
// Render example.com/orders
app.get('/orders', function(request, response) {
global.db.Order.findAll().success(function(orders) {
var orders_json = [];
orders.forEach(function(order) {
orders_json.push({id: order.coinbase_id, amount: order.amount, time: order.time});
});
// Uses views/orders.ejs
response.render("orders", {orders: orders_json});
}).error(function(err) {
console.log(err);
response.send("error retrieving orders");
});
});
// Hit this URL while on example.com/orders to refresh
app.get('/refresh_orders', function(request, response) {
https.get("https://coinbase.com/api/v1/orders?api_key=" + process.env.COINBASE_API_KEY, function(res) {
var body = '';
res.on('data', function(chunk) {body += chunk;});
res.on('end', function() {
try {
var orders_json = JSON.parse(body);
if (orders_json.error) {
response.send(orders_json.error);
return;
}
// add each order asynchronously
async.forEach(orders_json.orders, addOrder, function(err) {
if (err) {
console.log(err);
response.send("error adding orders");
} else {
// orders added successfully
response.redirect("/orders");
}
});
} catch (error) {
console.log(error);
response.send("error parsing json");
}
});
res.on('error', function(e) {
console.log(e);
response.send("error syncing orders");
});
});
});
// sync the database and start the server
db.sequelize.sync().complete(function(err) {
if (err) {
throw err;
} else {
http.createServer(app).listen(app.get('port'), function() {
console.log("Listening on " + app.get('port'));
});
}
});
// add order to the database if it doesn't already exist
var addOrder = function(order_obj, callback) {
var order = order_obj.order; // order json from coinbase
if (order.status != "completed") {
// only add completed orders
callback();
} else {
var Order = global.db.Order;
// find if order has already been added to our database
Order.find({where: {coinbase_id: order.id}}).success(function(order_instance) {
if (order_instance) {
// order already exists, do nothing
callback();
} else {
// build instance and save
var new_order_instance = Order.build({
coinbase_id: order.id,
amount: order.total_btc.cents / 100000000, // convert satoshis to BTC
time: order.created_at
});
new_order_instance.save().success(function() {
callback();
}).error(function(err) {
callback(err);
});
}
});
}
};
What does res.render do and what does the html file look like?
res.render() function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.
Answering Edit 2 part.
// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');
// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');
// here you render `orders` template
response.render("orders", {orders: orders_json});
So, the template path is views/ (first part) + orders (second part) + .ejs (third part) === views/orders.ejs
Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.
Renders a view and sends the rendered HTML string to the client.
res.render('index');
Or
res.render('index', function(err, html) {
if(err) {...}
res.send(html);
});
DOCS HERE: https://expressjs.com/en/api.html#res.render
I also had problems with res.render but it s using the template engine "pug" it was like this when I updated my http://localhost:3007/auth/login.
my route was:
router.get('/login', (req, res) => {res.render('auth/login)
now appeared like this with the new route.
router.get('/login', (req, res) => {res.render('auth/login.pug')});
always check out the route where our files are.
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.
I'm working with Node.js, express, mongodb, and got stuck on this data passing between frontend and backend.
Note: code below is middleware code for front- and backend communication
Here I successfully get the input value from the frontend by using req.body.nr
exports.find_user_post = function(req, res) {
member = new memberModel();
member.desc = req.body.nr;
console.log(req.body.nr);
member.save(function (err) {
res.render('user.jade', );
});
};
Here is the problem, I need to use the input value I got to find the correct data from my database(mongodb in the backend) and push out to the frontend.
My data structure {desc : ''}, the desc is correspond to the input value so it should look something like this {desc: req.body.nr} which is probably incorrect code here?
exports.user = function(req, res){
memberModel.find({desc: req.body.nr}, function(err, docs){
res.render('user.jade', { members: docs });
});
};
Would love to have some help.
Thanks, in advance!
Have a look at this great tutorial from howtonode.org.
Because as you can see he uses a prototype and a function callback:
in articleprovider-mongodb.js
ArticleProvider.prototype.findAll = function(callback) {
this.getCollection(function(error, article_collection) {
if( error ) callback(error)
else {
article_collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
exports.ArticleProvider = ArticleProvider;
in app.js
app.get('/', function(req, res){
articleProvider.findAll( function(error,docs){
res.render('index.jade', {
locals: {
title: 'Blog',
articles:docs
}
});
})
});
Also make sure you have some error checking from the user input as well as from the anybody sending data to the node.js server.
PS: note that the node, express and mongo driver used in the tutorial are a bit older.