Querying a Mongoose database in express.js using the "like" command for strings

Currently, I am trying to query my Mongoose database with a search parameter where the title matches the "customTitle" extracted from the URL.

The search function works perfectly fine when searching for all items using

Article.find(err, foundArticles) =>
. However, when attempting to specifically search for records containing the "customTitle" variable using
Article.find({title:/customTitle/i}, (err, foundArticles) => {
, I end up receiving an empty response.

My goal here is to retrieve a response that includes all items containing the "customTitle" variable within any record in the database.

app.route("/:customTitle")
.get(function(req, res){
  const customTitle = _.capitalize(req.params.customTitle);
  Article.find({title:/customTitle/i}, (err, foundArticles) => {
  if (!err){
    res.send(foundArticles);
    console.log(typeof customTitle +" ", customTitle);
    console.log(foundArticles);
  } else {
    res.send(err);
  }
});

If you could help me identify the issue at hand, I would greatly appreciate it. Thank you.

Answer №1

To generate the regular expression, utilize new RegExp. Your objective is to locate the exact string customTitle.

Here's an illustration:

const regex = new RegExp(customTitle, 'i')
query.find({title:regex})

Answer №2

I've discovered that utilizing RegExp in Mongoose and JavaScript is effective.

Here is an example of Mongoose RegExp in action:

app.route("/:customTitle")
  .get(function(req, res) {
    const customTitle = _.capitalize(req.params.customTitle);
    Article.find({ title: {$regex: customTitle, $options:'i'}}, (err, foundArticles) => {
      if (!err) {
        res.send(foundArticles);
      } else {
        res.send(err);
      }
  });

Additionally, here is an example of JavaScript RegExp being utilized:

  app.route("/:customTitle")
    .get(function(req, res) {
      const customTitle = _.capitalize(req.params.customTitle);
      const rx = new RegExp(customTitle, 'i');
      Article.find({title:rx}, (err, foundArticles) => {
        if (!err) {
          res.send(foundArticles);
        } else {
          res.send(err);
        }
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Vue app utilizing Flickr API encounters an issue: "Unable to assign value to 'data' property as it is undefined."

Beginning the development of a simple one-page photo stream app using the public Flickr stream, I've encountered an error in my code: 'Cannot set property 'data' of undefined'. Here is a snippet of my code: <b-container> ...

How to attach input to function invocation in Angular 2

Can we connect the @Input() property of a child component to a parent component's function call like this: <navigation [hasNextCategory]="hasNextCategory()" [hasPreviousCategory]="hasPreviousCategory()" (nextClicked)="next ...

Encountering an error while using $state.go function in Angular JS testing

Below is the code snippet for a Controller in Angular JS: describe('Controller: homeCtrl', function () { beforeEach(module('incident')); var homeCtrl, $state; beforeEach(inject(function ($controller, _$state_) { $state = _ ...

Steps for including a header and footer with page numbers in an HTML page without disrupting the rest of the content when printing

When I print a page with a table that spans multiple pages, I want to ensure that my header and footer are included on every page. The code I've tried so far has treated the entire content as one continuous page. How can I achieve this? ...

Changing text on a button with JavaScript toggle functionality: A step-by-step guide

I am looking to implement a feature where I can hide and show overflow content in a div. When I click on the expand button, it expands the content. However, I want this button to toggle and change text as well. Thank you! function descriptionHeightMo ...

Uncertainty arises from the information transmitted from the controller to the Ajax function

In one of my coffee scripts, I have an AJAX call that calls a method in a controller. The AJAX call is structured like this: auto = -> $.ajax url : '<method_name>' type : 'POST' data : <variable_name> ...

Failure occurs when attempting to send an object with an empty array using jQuery ajax

Looking to use jQuery Ajax PUT to send an object with an empty array `{value: {tags: []}}` to a Node.js express server, encountering the issue where `req.body.value` is undefined in the express `app.put()` handler. While suspecting jQuery as the culprit af ...

Running compiler-produced assembler code within the program

Recently, I came across an interesting presentation discussing inline ASM generation in Javascript optimization. The presentation can be found at the following link: . In another paper located here: https://sites.google.com/site/juliangamble/Home/Compiler ...

Transforming a value within a controller into a directive

I am uncertain if I am approaching this correctly, but my goal is to convert a piece of code from a controller to a directive. The reason for this change is that I want to reuse the code with different values without creating multiple large object literals ...

Content that is dynamically generated by a database

I have been working on creating a unique wall feature for my website, inspired by Facebook. My aim is to allow users to submit form data and have it validated before storing it in a database. Additionally, I want this stored data to be displayed in a desig ...

Utilizing JSON and select for dependency management

Let's say we have a JSON object: { "A": { "1": "1", "2": "2", "3": "3" }, "B": { "4": "4", "5": "5", "6": "6" }, "C": { "7": "7", "8": "8" } } And we also have ...

Make the jQuery toggle() function work like a regular radio button when selecting multiple options at a time

I have recently created two radio buttons using <i> font icons. Previously, I had successfully used the same code to create a checkbox, so I applied it to the radio buttons as well. After fixing the positioning, everything seemed fine when interactin ...

Trouble seeing span in ion-item in Ionic 2: How can I display plain text instead?

It seems like I may be overlooking something, as I am experiencing an issue with adding a span to an Ion Item, where the span is not being rendered, nor is the div. <ion-card> <ion-card-title> </ion-card-title> <div> < ...

Steps for removing every image from a folder

I'm currently facing an issue trying to remove all images from a directory. I'm encountering an error with the directory path and unsure of how to access and delete all image paths. Here is the structure of my directory : server -> app.js ...

CSS3 Perspective Issue: Solutions for Fixing

I'm currently working on creating a card flip animation that flips in the X axis direction. Right now, the div rotates using the rotateX() method. I attempted to add the perspective property to the upper div, but it ended up distorting my div structur ...

Turn off choices by utilizing data type attribute values within select2 version 4

I'm attempting to deactivate the options by using the data-type attribute specified for each option in select2. Unfortunately, my attempts have been unsuccessful thus far. In addition, I am encountering this error within the change event handler: ...

Node.js: Deciding between res.render and res.redirect in express-session

On my website, I have a login page and a myservices page. Once a user logs in, they should be redirected to the myservices page where their username is displayed. In the login.js file, the following code is used: req.session.user = "abc"; res.redirect(&a ...

The responsiveness of Slick Slider's breakpoints is malfunctioning

After implementing a slider using slick slider, I encountered an issue with the width when testing it online and in a normal HTML file. If anyone could assist me in resolving this issue, I would greatly appreciate it. Please inspect the code for both scen ...

Vue dynamic components fail to re-render within a v-for loop upon data changes

I've created a dynamic table component that allows me to modify columns by changing their ordering, adding new ones, or removing existing ones. The structure of my table body is as follows: <tr v-for="row in data" :key="row.id"& ...

What is the purpose of Access-Control-Allow-Headers in an HTTP response and why is it important to include it?

I've been working through a tutorial on using express and have come across the following routes: module.exports = function(app) { app.use(function(req, res, next) { res.header( "Access-Control-Allow-Headers", "x-ac ...