Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading