Home > Back-end >  MongoDB find user by search returning all users
MongoDB find user by search returning all users

Time:08-31

I am trying to query a user by their name field, and I am testing it in insomnia. I have my user schema like so:

const userSchema = mongoose.Schema({
  id: { type: String },

  name: {
    type: String,
    required: true,
  },
  companion: {
    type: String,
    required: false
  },
  bio: { 
    type: String,
    required: false
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
    min: 5
  },
  userImage: {
    type: String,
    required: false,
  },
});

And I have my route for /search which runs the getUserBySearch function: router.get('/search', getUserBySearch)

getUserBySearch logic:

export const getUserBySearch = async (req, res) => {
                         // tried req.query and req.query.search
  const { searchQuery } = req.params
  try {
              // make the search query not case sensitive
    const user = new RegExp(searchQuery, `i`)

    //find the user's name using the name field
    const userFound = await User.find({name: user})
    res.json({data: userFound})

  } catch (error) {
    res.status(404).json({message: error.message})
  }
}

Tested in insomnia under the route: http://localhost:3001/user/search?searchQuery=test

I should only be receiving the users whose name field include test; however I get back 200 response with ALL of the users in the DB. how can I only retrieve the users related to my search query?

CodePudding user response:

In your case http://localhost:3001/user/search?searchQuery=test, you should be accessing the ?searchQuery=test as req.query.searchQuery:

const { searchQuery } = req.query;
const user = new RegExp(searchQuery, `i`);

Since, you were wrongly reading the query value, you had undefined as a value for user constant, hence getting all users in the DB.

CodePudding user response:

exports.searchRecipe = async(req,res) => {
  try {
    let searchTerm = req.body.searchTerm;
    let user = await user.find( { $text: { $search: searchTerm, $diacriticSensitive: true } });
    res.render('search', {user} );
  } catch (error) {
    res.satus(500).send({message: error.message || "Error Occured" });
  } 
}

and in the search form try this,#

<form method="POST" action="/search">
            <input type="search" name="searchTerm"  placeholder="Search..." aria-label="Search">
        </form>

try like this ,

  • Related