Reputation: 183
Really appreciate some help in saving my hair that's left. I'm building a basic CRUD application using node.js + express + mongoDB + EJS. I gotta say, EJS has terrible documentation, making it really hard for us newbies to learn it. Here's the problem that I'm having.
I have an object called "vehicles" and I'm displaying it in a form select element. Here's my EJS:
<% vehicles.forEach(function(el){ %>
<option value="<%= el.vehicleModel %>"><%= el.vehicleModel %></option>
<% }); %>
Problem is, because it's picking up from object passed by MongoDB, it's not sorted. I went Googling and found this nice tutorial. EJS has filters that's (supposed) to solve this problem. So I tried the following code:
<% vehicles.forEach(function(el){ %>
<option value="<%=: el.vehicleModel | sort %>"><%=: el.vehicleModel | sort %></option>
<% }); %>
But it throws me the following error:
Object prototype may only be an Object or null
So I thought something was wrong with my code. I tinkered it with another filter (downcase) and used it like this:
<% vehicles.forEach(function(el){ %>
<option value="<%=: el.vehicleModel | downcase %>"><%=: el.vehicleModel | downcase %></option>
<% }); %>
And it works. The characters are undercased. Then why is the sort filter not working?
P/S: There goes another hair of mine..
Upvotes: 0
Views: 3238
Reputation: 5221
The sort filter takes an array as input, not a string. Something like the following would work:
<%=: vehicles | sort_by:'vehicleModel' | map:'vehicleModel' %>
Although it may not yield the same result you are looking for. In that case, you'll need to sort before hand in js. If the dataset of vehicle is quite large, I recommend sorting it right in the mongodb query.
Hope it helps.
Upvotes: 1