Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

506
Visualizações
Node.js how to use mongoose to do filter and pagination

I get all data successfully in my node.js code using Profile.find(),but when I want to add filter in api, it get 500 error.

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)
    })
})

I am new to mongoose and do not sure how to do the filter and pagination for my code. Appreciate for any kind help.

Update

Thanks to @Amila Senadheera, I finally find the solution to do filter and pagination using below code:

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

To use aggregation, it works like below:

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);
        }
      
    }
);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The find function can only accept query and projection as arguments. You are not allowed to give a callback as an argument. then should be chained to the Promise returned by find.

Try like this

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

Profiles with pagination.

you can use the MongoDB aggregation framework for that (which will make it possible to get additional information like the total entries and count of the entries on the current page (the last page might have a lesser number than the page limit)). You need to send start and limit as the request body.

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
            });
        }
    }
);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda