In my Nodejs api, I want users to be able to filter through data, like in the example below. I want users to be able to filter through places
based on the accessibility
or amenities
of the place model.
I have tried populating through the data, but for some reason, it seems that isn't the way to go about it to filter the data.
Please how can I go about this to filter the data based on the requirement?
below is my model
const mongoose = require('mongoose')
const placeSchema = new mongoose.Schema({
owner: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
title: {
type: String,
required: true,
trim: true
},
typeof: [{
type: String,
required: true,
enum: ["studio", "hall",
"house", "mansion",
"field", "room",
"restaurant", "school",
"church"
]
}],
description: {
type: String,
required: true,
trim: true
},
location: {
street: {
type: String,
required: true
},
city: {
type: String,
required: true
},
state: {
type: String,
required: true
},
country: {
type: String,
required: true
}
},
amenities: [{
type: String,
required: false,
enum: ["electricity", "air conditioning",
"wifi", "Bathrooms", "Sound System",
"Private Entrance", "Sink",
"Kitchen", "Large table",
"Green Screen", "TV", "Stage",
"changing room", "makeup room",
"lounge"
]
}],
accessibility: [{
type: String,
required: false,
enum: ["Wheelchair accessible", "Elevator",
"On-site parking", "Parking near by",
"Stairs"
]
}],
rules: {
type: String,
required: false,
trim: true
},
isOpen: {
type: Boolean,
required: false,
default: true
},
media: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Media',
required: false,
}],
// image related end
}, {
timestamps: true
})
const Place = mongoose.model('Place', placeSchema)
module.exports = Place
and below is the get request
// get all places
router.get('/api/place', async (req, res) => {
// pagination and filter
const noOnPage = parseInt(req.query.limit) || 10
const pageNo = (parseInt(req.query.page)-1)*parseInt(req.query.limit)
try {
const place = await Place.find({
isOpen: true
})
.select('-media')
.limit(noOnPage)
.skip(pageNo)
res.status(200).send(place)
} catch (e) {
res.status(500).send()
}
})
Here is how I tried populating which would not work
// get all places
router.get('/api/place', async (req, res) => {
// pagination and filter
const match = {}
if (req.query.amenities) {
match.amenities = req.query.amenities
}
const noOnPage = parseInt(req.query.limit) || 10
const pageNo = (parseInt(req.query.page)-1)*parseInt(req.query.limit)
try {
const place = await Place.find({
isOpen: true
})
.select('-media')
.limit(noOnPage)
.skip(pageNo)
.populate({
match
}).exec()
res.status(200).send(place)
} catch (e) {
res.status(500).send()
}
})
question from:
https://stackoverflow.com/questions/65921830/i-am-lost-on-how-to-filter-mongoose-data-based-on-some-options-in-nodejs