2017-04-04 20 views
1

嗨,我剛剛開始與編程,我想創建一個非常簡單的博客與Express.js和Mongoose.Whit這個代碼,我從我的數據庫打印6篇文章(簡單的文章架構:標題,內容和用戶)在我的博客的頭版。但我怎麼能不顯示整個內容,但只是從內容開始的100個字母。我如何將它傳遞給視圖?如何將substringed對象賦予視圖? Express.js

index: (req, res) => { 
    Articles.find({}).limit(6).populate('author').then(articles => { 
     res.render('home/index', { articles: articles}) 
    }) 
+0

你能提供HTML內容嗎? –

回答

0

取而代之的是:

res.render('home/index', { articles: articles }); 

你不得不使用:

res.render('home/index', { articles: articles.map(shorten) }); 

和實施shorten()功能如下:

function shorten(article) { 
    return { 
     title: article.title, 
     content. article.content.slice(0, 100), 
    }; 
} 

只要改變的關鍵名稱和content,因爲您沒有對數據的外觀做任何說明。

或者你可以改變這一點:

res.render('home/index', { articles: articles.map(shorten) }); 

喜歡的東西:

articles.forEach(article => { 
    article.content = article.content.slice(0, 100); 
}); 
res.render('home/index', { articles: articles }); 

如果你確定你不會需要在articles陣列的原始值更高版本。

+0

謝謝:)我用第二種方式做了它,它的工作就像我想要的那樣:) –

+0

「內容」。應該「爲內容:」​​爲對象屬性 –

相關問題