使用模型变量和forEach循环进行Mongoose排序

时间:2017-10-22 18:47:49

标签: node.js mongoose ejs

我有以下型号:

Favourites.getFav()

我想在show.ejs页面上使用类似的'order'变量值对此模型进行排序:

var lectureSchema = new mongoose.Schema({
    name: String,
    image: String,
    url: String,
    description: String,
    order: Number,
    free: Boolean,
    lectResOne: String,
    lectResTwo: String,
    lectResThree: String,
    lectResFour: String,
    extLinkOne: String,
    extLinkTwo: String,
    extLinkThree: String,
    extLinkFour: String
});

我正在使用mongoose版本:

<% lectures.sort().forEach(function(lecture){ %>
    <% if(lecture.free == false) { %>
        <div class="col-md-3 col-sm-6">
            <div class="thumbnail">
                <div class="abc">
                    <p class="centered-text"> <%=lecture.name%> </p>
                        <img src="<%= lecture.image %>">
                    <div class="caption">
                        <a class="btn btn-success btn-large" href="/lectures/<%= lecture._id %>">Begin</a>
                    </div>
                </div>
            </div>
        </div>
    <% } %>
<% }); %>

例如,我将有以下讲座:

讲义abc,订单价值为5

讲义d​​ef,订单价值为7

讲义ghi,订单价值为2

我希望这些从forEach循环输出按以下顺序显示:

2,5,7

由于

1 个答案:

答案 0 :(得分:0)

归功于摩尔达:

模型修改为:

var mongoose = require("mongoose");

var lectureSchema = new mongoose.Schema({
    name: String,
    image: String,
    url: String,
    description: String,
    order: Number,
    free: Boolean,
    lectResOne: String,
    lectResTwo: String,
    lectResThree: String,
    lectResFour: String,
    extLinkOne: String,
    extLinkTwo: String,
    extLinkThree: String,
    extLinkFour: String
});

// Code added to acheive lecture sorting on lectures and mlectures page.
var Lecture = mongoose.model('Lecture', lectureSchema);
Lecture.find().sort({ order: 1 });

module.exports = mongoose.model("Lecture", lectureSchema);

.ejs页面修改为:

    <% lectures.forEach(function(lecture){ %>
        <% if(lecture.free == false) { %>
            <div class="col-md-3 col-sm-6">
                <div class="thumbnail">
                    <div class="abc">
                        <p class="centered-text"> <%=lecture.name%> </p>
                            <img src="<%= lecture.image %>">
                        <div class="caption">
                            <a class="btn btn-success btn-large" href="/lectures/<%= lecture._id %>">Begin</a>
                        </div>
                    </div>
                </div>
            </div>
        <% } %>
    <% }); %>