2017-04-10 201 views
0

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> 

是我在航線代碼正確的?如何顯示index.js中的所有數據?請幫助。我是node.jsmongoDB的新手。謝謝:)

在mongo shell中,當我點擊db.users.find()時,它有兩個集合。我希望所需的輸出像這樣在索引中

username = "username1" 
path = "path1" 
originalname = "originalname1" 


username = "username2" 
path = "path2" 
originalname = "originalname2" 

是否有可能?喜歡做一些foreach的概念。

+0

模板引擎您使用的 –

+0

我用這d把手。這是index.handlebars –

+0

不是index.js。對不起這是我的錯。 –

回答

2
在.hbs

文件

可以使用迭代一個列表內置每個幫手。在塊內部,您可以使用它來引用正在迭代的元素。

<ul class="people_list"> 
    {{#each docs}} 
    <li>{{this}}</li> 
    {{/each}} 
</ul> 

並提供與對象文檔裏面陣列

[{}, {}, {}]

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

文檔是在這裏

Iteration in Handlebars

+0

它的工作原理。你真棒 –

0

讓我們考慮你在模型中有2個領域。名稱和_id。您需要將其渲染到視圖。

這裏你需要'ejs'模塊,一個模板框架來呈現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'); 

保持 'parentfolder /視圖' 裏面所有的意見..

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> 

這是ejs語法。

你的樣本輸出會是這樣

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

+0

@LawrenceRicafortBacus上面的代碼是'.ejs',你說你使用的是車把, http://handlebarsjs.com/builtin_helpers.html#iteration –

+0

歡迎:) @LawrenceRicafortBacus –

+0

@ p0k8_他提到他是新手,所以他只是需要一些解決方案,無論模板框架。如果在一個帶有車把的大型項目的中間實施,他會清楚地提到它。 –