Reputation: 137
I have a mongoose Schema like this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CitizenSchema = new Schema({
SSN: {
type: Number,
required: true,
unique: true,
},
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
}
});
const Citizen = mongoose.model('Citizen', CitizenSchema);
module.exports = Citizen;
and I have a route in my express app that is like this:
router.get('/', (req, res) => {
if (Object.keys(req.query).length === 0) {
// Get all the citizens if there is no query
Citizen.find({})
.select('-SSN')
.then((citizens) => res.send(citizens));
} else {
const query = req.query;
// Add case insensitive to all queries
for (const q in query) {
query[q] = {
$regex: new RegExp(query[q], 'i')
};
}
Citizen.find(query)
.select('-SSN')
.then((citizens) => res.send(citizens))
.catch((err) => res.status(400).send({ msg: 'Bad query request' }));
}
});
So what I do is that if there is not a query, I return all the citizens and if there is a query, I return the query result.
For example if I send a http request to my route with a GET request like http://localhost:5000/api/citizens/
, I get all the citizens. And if I send it with a query like http://localhost:5000/api/citizens/?lastName=Doe&firstName=john
, I only get the citizens with the first name as John and last name as Doe.
So my problem is that if I try and do a request like http://localhost:5000/api/citizens/?lastName=Doe&q=test
, I get an empty array and not the citizens that have Doe as their last name. The query q
makes it so that the Citizen.find()
does not work properly and does not return the result that I am waiting for.
I will be appreciate it if someone could help me fix this.
Upvotes: 1
Views: 107
Reputation: 656
You can try using $or
in your queries: https://kb.objectrocket.com/mongo-db/or-in-mongoose-1018
Upvotes: 2