Schema.js
var ItemSchema = mongoose.Schema({
username: {
type: String,
index: true
},
path: {
type: String
},
originalname: {
type: String
}
});
var Item = module.exports = mongoose.model('Item',ItemSchema, 'iteminfo');
route.js
router.get('/', ensureAuthenticated, function(req, res){
Item.find({},function(err, docs){
res.render('welcome', {docs:docs});
});
});
index.hbs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
[list of data here!!!]
</body>
</html>
Is my code in routes correct? how to display all data in index.js? Help please. I am a newbie in node.js and mongoDB. Thanks :)
In mongo shell, when I hit db.users.find(), It has two collections. I want the desired output to be like this in index
username = "username1"
path = "path1"
originalname = "originalname1"
username = "username2"
path = "path2"
originalname = "originalname2"
Is it possible? Like doing some foreach concept.
in your .hbs file
You can iterate over a list using the built-in each helper. Inside the block, you can use this to reference the element being iterated over.
<ul class="people_list">
{{#each docs}}
<li>{{this}}</li>
{{/each}}
</ul>
and for docs with objects inside array
[{}, {}, {}]
<ul class="people_list">
{{#each docs}} // iterating over array, and #each below loops the properties of elements {}
<li> {{#each this}} </li>
{{this}} // references the property values
{{/each}}
{{/each}}
</ul>
Docs are Here
Lets consider you have 2 fields in you model. Name and _id. You need to render that to the views.
Here you need 'ejs' module, a templating framework to render the data in the html.
Server.js
var express = require('express');
var app = express();
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
Keep all the views inside the 'parentfolder/views'..
routes.js
router.get('/', ensureAuthenticated, function(req, res){
Item.find({},function(err, docs){
res.render('welcome', {docs:docs}); // here the welcome should be the file name of the html you need to render
});
});
welcome.html
<table>
<% for(var i=0; i < docs.length; i++) { %>
<tr>
<td><%= docs[i].id %></td>
<td><%= docs[i].name %></td>
</tr>
<% } %>
</table>
Here is the ejs syntax.
Your sample output will be like this
<table>
<tr>
<td>1</td>
<td>bob</td>
</tr>
<tr>
<td>2</td>
<td>john</td>
</tr>
<tr>
<td>3</td>
<td>jake</td>
</tr>
This is my example, in this case I am iterating a body table
{{#each campaign}}
<tr>
<td>{{this}}</td>
<td>{{this._id.campaign}}</td>
<td>{{this.quantity}}</td>
</tr>
{{/each}}