Esquema.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');ruta.js
router.get('/', ensureAuthenticated, function(req, res){ Item.find({},function(err, docs){ res.render('welcome', {docs:docs}); }); });índice.hbs
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> [list of data here!!!] </body> </html> ¿Es correcto mi código en las rutas? ¿Cómo mostrar todos los datos en index.js ? Ayuda por favor. Soy un novato en node.js y mongoDB . Gracias :)
En Mongo Shell, cuando db.users.find() , tiene dos colecciones. Quiero que la salida deseada sea así en el índice
username = "username1" path = "path1" originalname = "originalname1" username = "username2" path = "path2" originalname = "originalname2" ¿Es posible? Como hacer algún concepto foreach .
en su archivo .hbs
Puede iterar sobre una lista utilizando cada asistente incorporado. Dentro del bloque, puede usar esto para hacer referencia al elemento que se está iterando.
<ul class="people_list"> {{#each docs}} <li>{{this}}</li> {{/each}} </ul>y para documentos con objetos dentro de la matriz
[{}, {}, {}]
<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>Los documentos están aquí
Consideremos que tiene 2 campos en su modelo. Nombre y _id. Necesitas representar eso en las vistas.
Aquí necesita el módulo 'ejs', un marco de plantillas para representar los datos en el html.
Servidor.js
var express = require('express'); var app = express(); app.set('views', __dirname + '/views'); app.engine('html', require('ejs').renderFile); app.set('view engine', 'ejs');Mantenga todas las vistas dentro de la 'carpeta principal/vistas'.
rutas.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 }); });bienvenido.html
<table> <% for(var i=0; i < docs.length; i++) { %> <tr> <td><%= docs[i].id %></td> <td><%= docs[i].name %></td> </tr> <% } %> </table>Aquí está la sintaxis ejs .
Su salida de muestra será así
<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>Este es mi ejemplo, en este caso estoy iterando una tabla de cuerpo
{{#each campaign}} <tr> <td>{{this}}</td> <td>{{this._id.campaign}}</td> <td>{{this.quantity}}</td> </tr> {{/each}}