【问题标题】:Node.js how to use mongoose to do filter and paginationNode.js如何使用mongoose做过滤和分页
【发布时间】:2022-01-25 11:06:44
【问题描述】:

我使用Profile.find()在我的node.js代码中成功获取了所有数据,但是当我想在api中添加过滤器时,它得到500错误。

Profile.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

//Create Schema
const ProfileSchema = new Schema({
    type: {
        type: String,
    },
    description: {
        type: String,
    },
    cash:{
        type: String,
        required: true,
    }
    
})

module.exports = Profile = mongoose.model("profile",ProfileSchema);

api.js

const router = express.Router();
const Profile = require('../../models/Profile');

router.get("/",passport.authenticate('jwt',{session:false}),(req, res) => {
    Profile.find().then(profiles => {
        res.json(profiles)
    })//works
     
})
router.get("/",passport.authenticate('jwt',{session:false}),(req, res) => {

    var condition = {'cash' : '5000'};
    Profile.find(condition,function(err,res){//error for this
        res.json(res)
    })
})

我是 mongoose 的新手,不知道如何为我的代码进行过滤和分页。 感谢您提供任何帮助。

更新

感谢@Amila Senadheera,我终于找到了使用以下代码进行过滤和分页的解决方案:

var condition = { cash: '5000' };
Profile.find(condition).skip(1).limit(10).then(profiles => { 
    res.json(profiles)
})

要使用聚合,它的工作原理如下:

router.post(
    "/",
    passport.authenticate("jwt", { session: false }),
      async (req, res) => {
        // page index
        let pageIndex = 1;
        // profiles per page
        let pageSize = 10;

        if (req.body.pageIndex !== null || req.body.pageIndex !== "undefined") {
            pageIndex = req.body.pageIndex;
        }

        if (req.body.pageSize !== null || req.body.pageSize !== "undefined") {
            pageSize = req.body.pageSize;
        }

        let condition = { description: "1" };
        try {
            const getAllProfile = await  Profile.aggregate([{
                $facet: {
                    data:[
                        { $match: condition },
                        { $skip: (pageIndex - 1) * pageSize },
                        { $limit: pageSize },
                       
                    ],
                    totalCount:[
                        { $match: condition },
                        { $count: 'totalCount' }
                    ]
                }
          
            }]) ; 
            res.json(getAllProfile);
        } catch (error) {
            res.status(404).json(error);
        }
      
    }
);

【问题讨论】:

  • 为什么您的ProfileSchema 没有cash 作为架构中的字段?
  • @Amila Senadheera 对不起,我忘了补充

标签: javascript node.js mongoose


【解决方案1】:

find 函数只能接受 queryprojection 作为参数。不允许将回调作为参数。 then 应该链接到 find 返回的 Promise

这样试试

var condition = {'cash' : '5000'};
Profile.find(condition).then(profiles => {
     res.json(profiles)
});

带有分页的配置文件。

您可以为此使用 MongoDB 聚合框架(这将可以获取附加信息,例如当前页面上的条目总数和条目数(最后一页的数量可能小于页面限制)) .您需要发送startlimit 作为请求正文。

router.get(
    "/",
    passport.authenticate("jwt", { session: false }),
    async (req, res) => {
        // page index
        let start = 0;
        // profiles per page
        let limit = 10;

        if (req.body.start !== null || req.body.start !== "undefined") {
            start = req.body.start;
        }

        if (req.body.limit !== null || req.body.limit !== "undefined") {
            limit = req.body.limit;
        }

        let condition = { cash: "5000" };

        try {
            const aggregatedData = await Profile.aggregate([
                {
                    $facet: {
                        data: [
                            { $match: condition },
                            {
                                $project: {
                                    type: 1,
                                    description: 1,
                                    cash: 1
                                }
                            },
                            { $skip: start * limit },
                            { $limit: limit }
                        ],
                        metaData: [
                            {
                                $group: {
                                    _id: null,
                                    count: { $sum: 1 }
                                }
                            }
                        ]
                    }
                }
            ]);
            return res.status(200).json({
                data: aggregatedData[0].data,
                metaData: {
                    total: aggregatedData[0].metaData[0].count,
                    start: start
                }
            });
        } catch (error) {
            return res.status(500).json({
                error: error
            });
        }
    }
);

【讨论】:

  • @Ryan,看看这个!!
  • 好的,我去看看,我的代码怎么分页?
  • 您可以使用mongodb聚合框架来获得分页工作
  • 哦,我搜索了一些文章,它们都用作回调,不知道原因,但它可以用作 Promise,谢谢
  • @Ryan,我已经更新了关于获取分页配置文件的答案。
猜你喜欢
  • 2012-08-28
  • 2014-01-17
  • 1970-01-01
  • 2020-01-21
  • 2022-07-11
  • 1970-01-01
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
相关资源
最近更新 更多