[英]Node.js How to display more than one category of articles on a page
我想用.limit()函數限制每個類別可以顯示多少個帖子,我不確定如何實現。
我正在使用貓鼬和Express。
到目前為止,我的代碼如下。
router.get('/', function (req, res) {
MainArticle.find({ category: ['Worldwide', 'U.S. News'] }, function (err, mainArticles) {
if (err) {
console.log(err);
} else {
res.render('landing', { mainArticles: mainArticles });
}
});
});
如果我要用EJS輸出結果,它將顯示兩個類別的所有結果。 如果我要限制,它將僅限制為我設置的整數。
我不確定要傳遞什么內容,因此我可以在網頁的不同部分顯示這兩篇文章,並限制要顯示的帖子數。
router.get('/profile', function (req, res) {
// Retrieve the desired count for each category (for example, through a query parameter) defaulting to some number as needed.
var limit = req.query.limit || 10;
// Create an object to hold the results
var result = {};
// Get data for the world wide category
MainArticle.find({
category: ['Worldwide'],
})
.limit(limit)
.exec(function (err, worldwideArticles) {
if (err) {
console.log(err);
} else {
// Add the worldwide data to the result set
result.worldwideArticles = worldwideArticles;
// Get data for the US news category
MainArticle.find({
category: ['U.S. News'],
})
.limit(limit)
.exec(function (err, usArticles) {
if (err) {
console.log(err);
} else {
result.usArticles = usArticles;
// Hand the two different sets separately to the template
// You will obviously have to change the template code to handle the new data structure of different categories
res.render('profile', { result: result });
}
});
}
});
});
EJS
<script type="text/javascript">
var json_data = <%= JSON.stringify( result ); %>
</script>
這將顯示“世界范圍”的文章,最多10條。
<ul>
<% result.worldwideArticles.forEach(function(mainArticles){ %>
<li>
<div class="img-container">
<a href="/articles/<%= mainArticles._id %>"><img src="<%= mainArticles.image %>" alt=""></a>
<div class="title-container">
<a href="/articles/<%= mainArticles._id %>"><%=mainArticles.title %></a>
</div>
</div>
<% }); %>
您可以在這里看看我將如何做。 讓我知道這個是否奏效。
router.get('/', (req, res) => {
MainArticle
.where('category')
.in(['Worldwide', 'U.S. News'])
.limit(10)
.then(mainArticles => {
res.render('landing', { mainArticles })
})
.catch(err => {
console.log(err)
})
)
}
您可能需要在此處進行選擇,但我無法對其進行測試。 如果不起作用,只需在.in之后添加要選擇的屬性。 例如.select('name', 'age', 'tags')
甚至更好的.select({})
但我不知道如果不進行測試,哪種方法將起作用。 我只是在這里關閉文檔:
http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html
閱讀Query API的另一種方法是這樣的:
router.get('/', (req, res) => {
const fetchArticles = MainArticle.find({})
fetchArticles
.where('category')
.in(['Worldwide', 'U.S. News'])
.limit(10)
.then(mainArticles => {
res.render('landing', { mainArticles })
})
.catch(err => {
console.log(err)
})
)
}
..或如果您想花哨:
router.get('/', async (req, res) => {
function getArticles() {
return MainArticle
.where('category')
.in(['Worldwide', 'U.S. News'])
.limit(10)
.exec()
}
try {
let mainArticles = await getArticles()
res.render('landing', { mainArticles })
} catch (error) {
console.log(error)
}
}
根據您的最后一次提交進行更新。
router.get('/', async (req, res) => {
function getWorldwideArticles() {
return worldwideArticles
.where('category')
.in(['Worldwide'])
.limit(10)
.exec()
}
function getUSArticles() {
return usArticles
.where('category')
.in(['U.S. News'])
.limit(10)
.exec()
}
try {
let worldwideArticles = await getWorldwideArticles()
let usArticles = await getUSArticles()
res.render('landing', { worldwideArticles, usArticles })
} catch (error) {
console.log(error)
}
}
我通過使用Chirag Ravindra發表並傳遞的內容解決了這一問題
<script type="text/javascript">
var json_data = <%- JSON.stringify( result ); %>
</script>
在我的EJS上我的forEach語句之上,因為EJS不能從客戶端調用變量
然后我就用
<% result.worldwideArticles.forEach(function(mainArticles){ %>
<% }); %>
<% result.usArticles.forEach(function(mainArticles){ %>
<% }); %>
我想發布兩個類別的地方。
一種方法是分別查詢每個類別,並通過在結果中的不同鍵上設置兩個find
操作的結果來構建模板的結果。
router.get('/', function(req, res) { // Retrieve the desired count for each category (for example, through a query parameter) defaulting to some number as needed. var limit = req.query.limit || 10; // Create an object to hold the results var result = {}; // Get data for the world wide category MainArticle.find({ category: ['Worldwide'] }) .limit(limit) .exec(function(err, worldwideArticles) { if (err) { console.log(err); } else { // Add the worldwide data to the result set result.worldwideArticles = worldwideArticles; // Get data for the US news category MainArticle.find({ category: ['US News'] }) .limit(limit) .exec(function(err, usArticles) { if (err) { console.log(err); } else { result.usArticles = usArticles; // Hand the two different sets separately to the template // You will obviously have to change the template code to handle the new data structure of different categories res.render('landing', result); } }); } }); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.