简体   繁体   中英

Node js, mongoose Sort data from database

Let's say I have a car collection. Now I would like to get cars that are red and have a mileage less than 100k km. Should I get all cars from database and make a function to filter cars or maybe mongoose have a function to filter this cars?

At the end, I would like to random 5 cars from this filter and display same cars to 5 different users in this same time. How should i do that?

I think this picture explains everything

https://i.stack.imgur.com/ZQNtb.png

you can pass filters directly into the mongoose query.

const cars = await Collection.find({
    Color: "red",
    Mileage: {
        $lt: 100
    }
}).limit(5);

i think you can use a mongoose query, like:

model.find({ color: red }).where('mileage').lt(100000);

mongoose docs (for more options like limit or sort)

and then just take a random function to filter the values again.

PS maybe there is a better solution in perspective of performance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM