Thursday 28 February 2019

Fix sort order for mongoose model

I have a mongoose schema:

models/profile.js

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var profileSchema = new mongoose.Schema({
    username: String,
    type: String,
    complete: {
        type: Boolean,
        default: false
    },
    email: { 
        type: String,
        default: ""
    },
    city: { 
        type: String,
        default: ""
    },
    position: { 
        type: String,
        default: ""
    },
    skills: Array
});

I am using this within an express framework, and on one page - shown below - I want to iterate over the key/value pairs and build a table.

I would like to retain the order designated in the Schema. Is it possible to set a sort order (or better yet, iterate over an unsorted object)?

Here's my profile.ejs file where I make the table:

<table class="table profile-display">
    <tbody>

    <% for(var key in profile.toObject({versionKey: false})) { %>
        <% if (key != '_id') { %>
            <% if (profile[key].length === 0){ %>
                <tr class="incomplete-warning table-rows">
            <% } else { %>
                <tr class="table-rows">
            <% } %>
                    <td class="key-text"><%=key.toUpperCase()%>:</td>
                    <td><%=profile[key]%></td>
                </tr>    
       <% } %>
    <% } %>

    </tbody>
</table>



from Fix sort order for mongoose model

No comments:

Post a Comment