Ich habe eine Sammlung von 200k Dokumente, die jeweils ein "CustomerName" -Feld enthält. Es gibt ungefähr 1k eindeutige "customerName" -Werte. (das Feld ist indiziert)Mungo - render verschiedene Werte und slugify diese Werte
Ich muss eine Liste dieser Kundennamen rendern und generieren Sie einen Slug für jeden, so dass ich in meinem Routing-URL verwenden kann.
Der nächste Schritt wäre, eine Seite für jeden customerName zu rendern, die alle Dokumente anzeigt, die diesen customerName enthalten. Hier
ist, was ich habe so weit,
/// 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>
Sind Schnecken nicht einzigartig? – Mikey