How to make a search controller using Express & MongoDB for my MERN project

Viewed 18

I'm creating a hotel booking application for my collage project. i'm trying to make a search controller like when we search anything they provide some similar suggestions like flipcart...

async search(req,res,next){
        const regex = new RegExp(req.params.place, 'i')
            try{
              const result = await HotelSchema.find({ city: regex }).select({ city: 1 }).limit(5);
              res.status(200).json(result);
            }catch(err){
            next(err);
            }
        }

Hotel Model:


const HotelSchema = new mongoose.Schema({
    name: { type: String, required: true },
    type: { type: String, required: true },
    city: { type: String, required: true },
    address: { type: String, required: true },
    distance: { type: String, required: true },
    photos: { type: [String] },
    description: { type: String, required: true },
    title: { type: String, required: true },
    rating: { type: Number, min: 0, max: 5 },
    rooms: { type: [String]},
    cheapestPrice: { type: Number, required: true },
    featured: { type: Boolean, default: false },
});

export default mongoose.model("Hotel", HotelSchema, "hotels");

Here is my code and i want to search by city field. If anyone have any suggestion feel free to tell me.

0 Answers
Related