[英]mongoose - render distinct values and slugify those values
我有20萬個文檔的集合,每個文檔包含一個“ CustomerName”字段。 大約有1k個唯一的“ customerName”值。 (該字段已編制索引)
我需要呈現這些客戶名稱的列表,並為每個客戶名稱生成一個標簽,以便可以在路由URL中使用。
下一步將是為每個customerName呈現一個頁面,該頁面顯示包含該customerName的所有文檔。
到目前為止,這就是我所擁有的,
/// Customer.js
const rmaSchema = new Schema({
CustomerName: { type: String, index: true },
slug: String },
{ collection : 'mycompany' // collection name
});
rmaSchema.pre('save', function(next) {
this.slug = slugify(this.CustomerName) ;
next();
});
const rmaModel = mongoose.model('Rma', rmaSchema);
module.exports = rmaModel;
// function to slugify a name
function slugify(text) {
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
/// Customer.Controller.js
function showCustomers(req, res){
Rma.distinct('CustomerName', function(err, customers) {
if (err){
res.status(404);
res.send('customers not found!');
}
res.render('pages/customers', {customers: customers});
});
};
module.exports = showCustomers;
/// customer.ejs
<table class="table table-bordered table-hover table-striped">
<tbody>
<% for (var customer of customers) { %>
<tr>
<td><%= customer.CustomerName %></td>
<td><a href="/events/<%= customer.slug %>" class="btn btn-sm btn-primary">Generate Report</a></td>
</tr>
<% } %>
</tbody>
我在那里不太了解您的控制器邏輯,但僅是我們有話要說,這里是您如何引用路徑中的段的信息:
app.get('/rma/:slug', function(req, res, next) {
console.log(req.params.slug)
// mongo query to find slug
if (foundRecord) {
return res.render('pages/customer', {
customer: foundRecord
})
} else {
return res.render('404', { slug: req.params.slug })
}
})
您的子彈功能看起來不錯。
我想提到的一件事是,在您當前的控制器中,您沒有使用顯式return
,因此需要特別注意的是,如果用戶達到該404條件,則您的API將為此設置標頭,並且可以繼續。 我不確定使用res.send對此有100%的把握,但是您絕對可以將兩者都更改為return res.send()
和return res.render()
來對其進行強化。 返回值將確保它在那一刻退出函數。
如果您遇到拍打和拍打的問題,建議您將拍打與記錄一起存儲,如果用戶更新了他們的姓名,也請對其進行更新。
{
_id: 'g9sd76gft9s87dfgs8d7f'
CustomerName: 'Bob Alice',
CustomerNameSlug: 'Bob-Alice'
}
正如上面Mikey在評論中所提到的,如果您沒有獨特的子彈,您將在路線中遇到命名沖突。
為了解決這個問題,如果您將條塊與每個記錄一起存儲在Mongo DB中,則可以采用使其獨特的方式,但是只有當您的客戶僅通過單擊UI而不是手動輸入到達路線時,我才會這樣做網址。 您可以執行類似slugify(
$ {CustomerName} $ {timestamp} )
,以提供合理的唯一保證。
嗯,我在那兒使用了模板字符串,由於使用了雙重嚴重的重音符號,StackOverflow語法熒光筆似乎不太喜歡。 要明確的是,這將獲得與slugify(CustomerName + timestamp.toString())
相同的結果。 這只是一個簡單的串聯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.