ExpressJS在路由文件中排序模式对象

时间:2014-11-20 02:43:34

标签: javascript node.js sorting express mongoose

我希望按最近的日期对数据库信息进行排序,作为第一个对象,然后按降序排列。目前我的数据顺序相反,我不知道应该在哪里调用排序方法,因为我没有使用.find方法。我试过了

`.get(function(req, res, next) {

Blogpost.paginate({}, req.query.page, req.query.limit, {sort: ['dateString', -1]}, function(err, pageCount, blogpost, itemCount) {`

但我收到了TypeError: object is not a function

这是我的模特:

blogModel.js

var mongoose    = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var Schema      = mongoose.Schema;



var BlogPostSchema  = new Schema({
        title: String,
        blogUrl: String,
        author: String,
        tagline: String,
        category: String,
        content: String,
        tags: { type: String, lowercase: true },
        date: { type: Date, default: Date.now() }
});

BlogPostSchema.post('init', function (post) {
    var date = new Date(post.date || Date.now() );
    post.dateString = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();

});

BlogPostSchema.plugin( mongoosePaginate );

var Blogpost = mongoose.model("Blogpost", BlogPostSchema);



module.exports = mongoose.model('Blogpost', BlogPostSchema);

routes.js

var express = require('表达');

var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');

//index 
router.use(paginate.middleware(10, 50));




    router.route('/') 


        // START GET method
        .get(function(req, res, next) {

            Blogpost.paginate({}, req.query.page, req.query.limit, {sort: ['dateString', -1]}, function(err, pageCount, blogpost, itemCount) {




                if (err) return next(err)

                        if (err)
                            res.send(err);




                        res.format({
                            html: function() {
                                res.render('pages/index', {
                                    blogpost: blogpost,
                                    pageCount: pageCount,
                                    itemCount: itemCount
                                })
                            },
                            json: function() {

                                res.json({
                                    object: 'blogpost',
                                    has_more: paginate.hasNextPages(req)(pageCount),
                                    data: blogpost
                                })
                            }
                        }); // END res.format(html, json)
            }); // END Blogpost.paginate
        }); // END GET method

router.route('/admin/posts/create')

    // START POST method
        .post(function(req, res) {

            console.log("New instance");

            var blogpost = new Blogpost(); // create a new instance of a Blogpost model

            blogpost.title = req.body.title; // set the blog title
            blogpost.blogUrl = blogpost.title.toLowerCase().replace(/\s+/g,"-");
            blogpost.author = req.body.author; // set the author name
            blogpost.tagline = req.body.tagline; // set the tagline
            blogpost.content = req.body.content; // set the blog content
            blogpost.category = req.body.category; // set the category
            blogpost.tags = req.body.tags; // set the tags
                //Save Blog Post
                blogpost.save(function(err) {
                    if (err)
                        res.send(err);

                    res.redirect(303, '/'); //NEEDS TO BE CHANGED
                });

        }) // END POST method

index.ejs:

<div class="blog-content">
                <% blogpost.forEach(function(blogpost) { %>
                    <tr>
                        <td><h2><a href="/blog/<%= blogpost.blogUrl %>" class="blog-title"><%= blogpost.title %></a></h2></td>
                        <td><h3><%= blogpost.dateString %></h3></td>
                        <td><h3 class="blog-category"><%= blogpost.category %></h3></td>
                        <td><h3 class="blog-tagline"><i><%= blogpost.tagline %></i></h3></td>
                        <td><p><%=: blogpost.content | truncate:800 | append:'...' %></p></td>
                        <td><a href="/blog/<%= blogpost.blogUrl %>" class="blog-read-more">Read More</a></td>
                    </tr>
                    <% }); %>
            </div>

1 个答案:

答案 0 :(得分:0)

之前我没有使用过paginate插件,但看起来paginate插件会出现非标准options参数来回调后。 :(

看起来sort属性存在问题。

发生TypeError: object is not a function错误,因为分页代码试图将您的选项哈希作为函数调用。 https://github.com/edwardhotchkiss/mongoose-paginate/blob/master/lib/mongoose-paginate.js#L54

应该是这个:

Blogpost.paginate({}, req.query.page, req.query.limit, 
    function(err, pageCount, blogpost, itemCount) {
 ...
}, {sort: {'date': -1 } );

或者这个,因为我觉得mongoose做了一个非标准的&#34; sortBy&#34;而不是&#34;排序&#34;。

Blogpost.paginate({}, req.query.page, req.query.limit, 
     function(err, pageCount, blogpost, itemCount) {
 ...
}, {sortBy: {'date': -1 } );

你实际上并不想按&#34; dateString&#34;排序。因为它不是真的在数据库中。按&#34;日期&#34;排序并使用dateString进行渲染。此外,呼叫字段&#34;日期&#34;可能是次优的,因为它在很多地方被用作关键字。我把它称为创建日期或其他一些。