Rahul Gupta
Rahul Gupta

Reputation: 5

fetch data between min and max price from mongodb using node js

I am trying to fetch data between min and max price from property model

e.g.if user inputs min and max price then the number of properties between that min and max price will show

i have indexed the $text in for type and tags value

I am new to mongodb.. appreciate the help. thankyou

here is my controller code

searchProperty = async (req, res) => {
const property = await Property
// first find the property that matches
.find({
    $text: {
        $search: req.query.q
    }
}, {
    score: { $meta: 'textScore' }
})
// then sort them
.sort({
    score: { $meta: 'textScore' }
})
// limit to only 5 result
//.limit(5)
res.json(property); };

here is my model

const propertySchema = new mongoose.Schema({
name: {
    type: String,
    trim: true,
    required: 'Please enter your name!'
},
status: {
    type: String,
    required: 'Please enter the status!'
},
type: {
    type: String,
    required: 'Please enter your type!'
},
rooms: {
    type: String,
    required: 'Please enter your no of Rooms!'
},
old: String,
bedrooms: String,
bathrooms: String,
phone: Number,
title: {
    type: String,
    trim: true,
    required: 'Please enter your property title!'
},
price: {
    type: Number,
    required: 'Please enter your Price!'
},
area: Number,
description: {
    type: String,
    trim: true,
    required: 'Please enter your description!'
},
zipcode: Number,
slug: String,
tags: [String],
created: {
    type: Date,
    default: Date.now
},
location: {
    type: {
        type: String,
        default: 'Point'
    },
    coordinates: [{
        type: Number,
        required: 'Please enter the Coordinates!'
    }],
    address: {
        type: String,
        required: 'Please enter the Address!'
    }
},
author: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
    reuqired: 'You must supply an author'
} });
   // Define our indexes
   propertySchema.index({
    type: 'text',
    tags: 'text'
  });

here is my route

router.get('/api/v1/search', searchProperty);

Upvotes: 0

Views: 1368

Answers (1)

Abhyudit Jain
Abhyudit Jain

Reputation: 3748

You can use $gte and $lte for this.

db.properties.find({price: { $gte: 1, $lte: 1000 } } );

This will fetch the properties with the price between 1 and 1000.

Upvotes: 2

Related Questions