如何使集合中的mongodb文档按降序排序?

时间:2020-05-02 17:53:57

标签: reactjs mongodb express

所以我有一个Post模型,在其中添加了一个orderIndex道具用于排序:

const mongoose = require('mongoose');

const Post = mongoose.model(
    'Post',
    new mongoose.Schema({
        title: { type: String, trim: true },
        content: { type: String, trim: true },
        picture: {
            mimeType: { type: String, default: '' },
            thumb: { type: String, default: '' },
            fileName: { type: String, default: '' },
        },
        author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
        orderIndex: { type: Number, default: 0 }
    }, { timestamps: true })
);

module.exports = Post;

,在获取所有帖子的控制器中,我添加了sort()函数,如下所示:

User
        .findById(req.params.userid)
        .sort({ orderIndex: -1 })
        .populate('posts', 'title content createdAt')
        .exec((error, user) => {
            if (!user.posts) {
                return res.status(404).json({
                    message: 'No posts found',
                });
            }

            if (error) {
                res.json({ message: error.message, });
            }

            res.status(200).json({ posts: user.posts });
        });

在react组件中,我像这样进行axios校准:

const fetchPosts = () => {
            axios.get(`${keys.SERVER_URL}/post/get-posts/${isAuthenticated()._id}`)
                .then((response) => setPosts(response.data.posts))
                .catch((error) => console.log(error.response.data.message));
        };

,但帖子仍未排序。如何使帖子按降序排列?

0 个答案:

没有答案
相关问题