Filter with Node.JS

Asked

Viewed 1,167 times

1

I have a list of items saved in a Mongo collection, I would like to know how to filter the original array. Follows the code

api.filtra = function (req, res) {
    model.find()
        .then(function(itens) {
            for(i = 0; i < itens.length; i++)
                console.log(itens[i].criterio);                
                res.json(itens);

                console.log("testeA");
                var filtrado = itens.filter(
                    itens, {"genero": "0"}
                );
                console.log("testeB");               
                console.log(filtrado);
        }, function (error) {
            console.log(error);
            res.sendStatus(500);
        });
}

The problem with this code is that it hangs when it comes time to execute the "items.filter", the last thing it displays on the console is the "testeA"
What I’d like to do is for example, say I had people in this array, pass as a parameter via url to age, more or less like '/v1/people/age/x' where x is the user’s chosen age, and so only send to the browser the list with the people who already meet this criterion.
I hope I have been able to explain my doubts well, but if I have been confused tell me that I will try to rephrase my question.
Thank you all from now on.

  • What is the Mongo property that corresponds to age?

  • {"_id":"59ab81944356843198769bcb" "name":"João" "age":20 "address":"Rua X, Bairro Y, Rio de Janeiro" "occupation":"student" "sex":"male" ":0}

1 answer

1


Why don’t you let the mongodb do it for you, search the mongodb using his querry... ex:

model.find({idade:req.query.idade}).then((result) => {
     res.json(result)
}, (err) => {
     res.status(500).json({error: err})
})

This way you could call as follows: /api/people? age=15. I recommend you a studied on the patterns of a Restfull api

Browser other questions tagged

You are not signed in. Login or sign up in order to post.