Querying Mongoose using the find method to retrieve data and return the name of the field where the results were found

Is it possible to retrieve the field or fields in which a regex match was found in my query result? For example:

If I find a result in the 'facebook' field;

Let's say my req.body.key = 'crazy' and inside my database, I have 'crazy' in the 'facebook' field. I would like the output of the query to include the CitizenProfile model along with the name of the field where the result was found. In this case, the field name would be 'facebook'

Note: The query currently provides the model, but I also need the name of the field(s) where the regex match is found. Is this feasible? Thank you!

    app.post('/v1/profile/search', (req, res) => {
    async.waterfall([
        function (next) {
            CitizenProfile.find({
                $or: [{'first_name': {$regex: req.body.key, $options:'i'}}, {'middle_name': {$regex: req.body.key, $options:'i'}},
                    {'last_name': {$regex: req.body.key, $options:'i'}}, {'email': {$regex: req.body.key, $options:'i'}},
                    {'facebook': {$regex: req.body.key, $options:'i'}}, {'linkedin': {$regex: req.body.key, $options:'i'}},
                    {'skills': {$regex: req.body.key, $options:'i'}}],
                'id_citizen': {$ne: req.body.id_citizen},
                'is_hidden': {$ne: true}
            })
                .exec(function (err, data) {
                   ...

Answer №1

As far as I know, MongoDB does not offer this specific feature (but feel free to correct me if I'm mistaken).

When retrieving documents that match a regular expression, you'll need to reapply the same regular expression on those retrieved documents to locate the desired fields.

Although it hasn't been tested, one possible approach could be:

let regex = new RegExp(req.body.key, 'i');

CitizenProfile.find({
    $or: [
        { 'first_name': regex },
        { 'middle_name': regex },
        { 'last_name': regex },
        { 'email': regex },
        { 'facebook': regex },
        { 'linkedin': regex },
        { 'skills': regex }
    ],
    'id_citizen': { $ne: req.body.id_citizen },
    'is_hidden': { $ne: true }
}).exec(function (err, profiles) => {
    // iterate through the discovered documents
    profiles.forEach(function (profile) {
        profile = profile.toJSON();
        // extract fields based on the regular expression
        let keys = Object.keys(profile).filter(k => regex.test(profile[k]));
        // perform actions with the identified keys
        console.log(keys);
    });
});

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

What is the best way to modify an Li element using the DOM in JavaScript?

Just the other day, I discovered how to use JavaScript and DOM to add and delete Li elements. Now I'm curious about how to edit those Li elements using DOM. Any suggestions? Thank you! ...

Converting JavaScript functions to Java remote method interfaces

Experience: A while back, I was involved in developing a Java Server-Client application for building automation purposes. Initially, we used Java RMI to connect the server and client but soon realized that utilizing JavaScript for the client side would be ...

Sorting the keys of objects within an array

Currently, I am in the midst of an evaluation where I have the freedom to utilize any resources at my disposal. The task at hand involves using the .filter method to remove objects without a specific key. Here is the provided prompt... Create a function n ...

Moving the words from textArea to each 'ol' element using JavaScript

When a word is entered in the textarea, it should be assigned to a specific class within an 'ol' tag. Each subsequent word will be placed in the next class sequentially. If there are no more words, the remaining classes should remain empty. <! ...

Incorporating Tinymce into a dialog with Vuejs & Vuetify may necessitate a refresh

I have implemented tinymce as a component for creating and editing articles In addition, I am using vuetify along with the v-dialog component, and all my form fields are within this modal However, each time I change the instance of the tinymce component, ...

Adjust the texture rotation on a PlaneGeometry by 45 degrees using UV coordinates

Trying to apply a rotated texture onto a PlaneGeometry has been a bit of a challenge for me. I have a 44x44 diamond-shaped texture that you can view here: https://i.sstatic.net/Babx0.png My goal is to map this diamond texture onto the plane geometry usi ...

Steps for organizing values based on the selected value from the dropdown menu in a select option

I have two drop down menus, defined as follows: <select name="" id="district" onchange="selectbyDistrict()"> <option value="one">1</option> <option value="two">2</option> <option value="three">3</option&g ...

JavaScript maintaining records and connections between multiple asynchronous events

I am working on an Angular 10 project where users can compress and upload images to Google Cloud Storage. The compression and uploading functionalities are functional, but I'm facing challenges with managing the asynchronous process of handling multip ...

The Child component is unable to render initially due to the Context API being undefined during the first render of the Child component

I'm struggling to ensure that a child component only renders when the Context API state I've set up is fully mounted. The Parent component fetches data from the server and sets the state based on the received information. Initially, I keep gettin ...

How to Keep Bootstrap 3 Accordion Open Even When Collapsed

I am in the process of building an accordion group with bootstrap 3. Here is the code I have so far: <div id="accordion" class="panel-group"> <div class="panel panel-default"> <div class="panel-heading"> <div class ...

issue with implementing the chart.js npm package

Just recently, I added chart.js to my project using npm. My goal is to utilize the package for creating graphs. npm install chart.js --save After the installation, I attempted to import the module with: import chart from 'Chartjs'; However, t ...

What is the best way to establish a default format for converting dates into strings?

When storing dates in MongoDB, I typically use a field of type Date which looks like this: startDate: 2019-12-14T09:00:00.000+00:00 To prevent timezone shifting when utilizing the date on the client side without the "Z" at the end, I prefer the format 20 ...

JS: When the 'less than' operator falls short

I am facing an issue with a script that sends an AJAX request every 10 seconds (technically 11) to the user. I have created a simple countdown from 10 to 0 that repeats continuously. The countit function is triggered after each AJAX request to reset the c ...

Unable to establish header once it has been sent

Here is my code: function handleToken(response, error, token) { if (error) { console.log("Error retrieving access token: ", error.message); response.writeHead(200, {"Content-Type": "text/html"}); response.write('<p>ERROR: ' + ...

Utilize Unity's dependency injection with MongDb integration

My Repository code currently looks like this: public MyRepo(ILog logger) { this.Logger = logger; var mongoUrlBuilder = new MongoUrlBuilder(ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString); this.MongoClient = new MongoClie ...

Ways to initialize event handlers within a loop?

There are a total of three buttons on my page. Each button, when clicked, should display the number of the button in a <span> element. <button>1st button</button> <button>2nd button</button> <button>3rd button</butto ...

Leveraging the power of tabs in AngularJS

Utilizing tabs in angularjs and dynamically loading views. My goal is to prevent the re-loading of a view that has already been loaded, and to ensure that the controller does not run again when using $state.go. Instead, it should be set to active status. ...

Conceal the excess content by placing it behind a series of stacked div

Within my layout, there is a fixed div called #navigation that houses buttons. Alongside this, there is scrollable content in the form of .card elements. The #navigation div currently displays with a green background for demonstration purposes, as shown b ...

Searching for and modifying a specific subdocument with Mongoose in a node.js environment

I am presenting a Schema similar to the following, const UserSchema = new Schema( { name: { type: String, required: true }, payment:[{ description: { type:String }, amount:{ type:String }, ...

What is the best way to link a CSS file within a PHP document's head section and a JavaScript file just before the closing body tag?

How can I properly include a CSS file in the head section of a PHP file? Currently, I am including CSS like this: <?php include('./includes.header.html'); ?> <style><?php include('./test.css'); ?> </style> The ...