What is the best way to query for a mongoose ObjectId within feathers?

With two feathers services at hand, one for handling profiles and another for labels, the possibilities are endless.

In a profile, you can have an array of ObjectId labels from other collections. Imagine the depth of connections!

Now, picture this scenario: a user enters "linux" in the search input field.

The profile named foo should be retrieved because it contains the ID "594ceeff6905e622425f523b" in its labels array.

Is this kind of search query, involving ObjectIDs between objects, feasible using Feathers?

Profiles

Mongoose model

{
    name: { type: String, trim: true, required: true },
    labels: [{ type: ObjectId, ref: 'Labels' }],
}

Feathers API response for profiles

Accessible via: http://localhost:3030/profiles

{
    "name": "foo",
    "labels": [
        "594ceeff6905e622425f523b",
        "594ceeff6905e622425f523c",
        "594ceeff6905e622425f523d"
    ],
}

{
    "name": "bar",
    "labels": [
        "594ceeff6905e622425f523e",
        "594ceeff6905e622425f523d"
    ],
}

Labels

Mongoose model

{
    name: { type: String, trim: true, unique: true, required: true },
}

Feathers API response for labels

Accessed through: http://localhost:3030/labels

{
    "_id": "594ceeff6905e622425f523b",
    "name": "linux"
},
{
    "_id": "594ceeff6905e622425f523c",
    "name": "systemd"
},
{
    "_id": "594ceeff6905e622425f523d",
    "name": "mongodb"
},
{
    "_id": "594ceeff6905e622425f523e",
    "name": "javascript"
}

But as the list of labels grows, populating all labels into the profiles response, sending them all to filter on the frontend based on the search value might not be the most efficient approach.

There must be a better way to handle this as the database expands. Any ideas?

Answer №1

If you want to implement a search functionality, you can use code similar to the following:

Profile.find({}).populate({
    path: 'labels',
    match: {
        name: { 
            $regex: new RegExp(searchText, 'i'); 
            //searchText is passed from the front end.
        }
    } 
}).then(function(profiles){
  var filteredProfiles = profiles.forEach(function(profile){
    return profile.labels; //will be null for items that don't match the searching regex.
    //resolve the filtered profiles to the front end.
  })
},function(error){
  //Handle any errors here
})

Answer №2

Feathers allows you to utilize all the features of Mongoose itself, and if you have specific requirements, you can make use of the Mongoose query population functionality.

The feathers-mongoose adapter facilitates this by supporting the $populate query parameter for querying purposes.

http://localhost:3030/labels?$populate=labels

This should meet your requirements effectively.

Answer №3

In the conclusion, I simplified the process by making just two calls to the API:

computed: {
    ...mapState('profiles', { profiles: 'keyedById' }),
    ...mapState('labels', { labels: 'keyedById' }),
},

methods: {
    ...mapActions('profiles', { findProfiles: 'find' }),

    async fetchData() {
        const labels = this.labels;
        const searchTerm = this.search_input.toLowerCase();

        // Create an array of matched labels per profile
        const labelIds = Object.keys(labels).filter(label => {
            const name = labels[label].name.toLowerCase();
            return name.includes(searchTerm);
        });

        // Search for profiles based on name or labels
        this.findProfiles({
            query: {
                $or: [
                    {
                        name: { $regex: searchTerm, $options: 'igm' },
                    },
                    { labels: { $in: labelIds } },
                ],
                $populate: ['user'],
                $sort: { updatedAt: -1 },
            },
        });
    },
},

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

Customizing Electron Protocol with oAuth redirection

In my current project using discord oAuth2 within a vue/nuxt/electron application, I am in need of creating a custom protocol to handle the oAuth2 code. Ultimately, I am hoping to achieve a structure similar to this: myapp://auth/callback?code=codehere De ...

An illustration of the fundamental concepts of require.js

main.md <markdown> <head> <script data-main="script" src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script> </head> <body></body> </markdown> script.css defi ...

Retrieving HTML file from server directory within extjs HTML editor

Can anyone help me figure out how to successfully load an HTML file into the code editor? I have attempted using the code below, but it doesn't seem to be working: loader : {url : 'uploads/temp.html', autoload : true} ...

What are some ways to make session variables available for sub applications?

I am currently working on setting up an API to interact with a MongoDB database, which I have integrated as a subapplication. In my server controller, I have created a session variable. However, I am facing an issue where the session variables are not be ...

What is the method for adding <option> tags to a <select> statement using a for loop?

Currently, I am facing a challenge in dynamically populating the <option> tags within a <select> menu. My approach involves using a for loop in JavaScript to cycle through the number of options and append them to the select tag. The part of th ...

Issue with Material UI tool tip not closing upon clicking on an element is persistent

Check out this link for a material UI tooltip demo I have been experimenting with the material UI tooltip in the provided link. The tooltip pops up when hovering over the button, but it doesn't disappear when clicking on the button. Is this the defau ...

Methods for transferring data to controller in Angular Modal service

After implementing the angular modal service discussed in this article: app.service('modalService', ['$modal', function ($modal) { var modalDefaults = { backdrop: true, keyboard: true, m ...

Enhance the functionality of a form by dynamically adding or deleting input rows using

The feature for adding and deleting input rows dynamically seems to be experiencing some issues. While the rows are successfully created using the add function, they are not being deleted properly. It appears that the delete function call is not function ...

`Inability to remove item from array in Vue.js`

I've been struggling to understand why this feature isn't functioning as expected. I'm using sample code for reference, but it's not behaving the same way. When I click on the delete button, nothing happens even though it should remove ...

Pass the initial value from a parent component to a child component in ReactJS without the need for state management

Initially, I have a parent Component A that calculates an initial value for its child Component B. The initial value is computed in the componentDidMount() of Component A and passed to B using props: <ComponentB initialValue={this.state.value} handleCha ...

"Encountering issue with componentDidMount() not functioning as expected, despite debugger being

Hello everyone! This is my first time sharing something here, so I'm eager to hear your feedback on both how I've posted and the content itself. I've only been programming for 8 weeks now, so I'm sure there are plenty of mistakes in wha ...

Enhancing the aesthetic appeal of a form

I have created a form in HTML that utilizes JavaScript to pull data from a database. I am looking to style the form, but I'm unsure of how to proceed. Below is the form along with some CSS code. How can I integrate the two together? <form id=" ...

Querying for a referenced item using Mongoose

My database schema is structured in a way that resembles the following: User_A { a_array: [{ b: { type: Schema.Types.ObjectId, ref: 'User_B' } }] } User_B { b_name:String } I am trying to figure out how many unique User_As co ...

Updating the columns in a row by clicking the refresh button with ajax in a JSP file

Hey there! I have a table on my JSP page with refresh buttons at the row level. When I click the refresh button, it should check the database and update those two columns with new values. Below is the code snippet for my JSP page: <script src="js/jque ...

Utilizing React Native for seamless deep linking with automatic fallback to a webpage, including the ability to pass

I am currently working on a project that involves a website built with React and a React-native app for camera functionality and data processing. On the website, there is a button that opens the camera in the React-native app through deep-linking. This pa ...

Is it possible to only make the text in a Bootstrap button act like a link, instead of the whole button itself?

As I start learning HTML and CSS with the help of Bootstrap, I'm encountering an issue with button functionality. The text within the button is acting like a link, but the entire button should be clickable. I'm not sure if I need more than just t ...

When a HTML table is generated from imported XML, DataTables will be applied

I am facing a challenge with my code and would appreciate some help. I am trying to load an XML file using jQuery and then use DataTables on my HTML table. However, the plugin doesn't seem to be functioning correctly. When I manually create an HTML ta ...

Exploring the combination of Holder.js and Rails routes

What's the best way to integrate Holder.js into my Rails application? I'm running into issues where Rails is interpreting the parameters passed to the script as routes and returning 404 errors. Has anyone successfully implemented this before? ...

What is the best way to use ajax for uploading multiple images at once?

I'm having trouble uploading multiple image files. Can someone please review my code? <form id="fileupload" method="POST" enctype="multipart/form-data"> <input type="file" name="files[]" multiple="multiple" id="images_input"> & ...

Using Ajax to transmit a model from a list traversed by a foreach loop to a controller

When sending a list of a model back to the controller from a view, I want it to happen only when the input has been checked. Although using AJAX makes it work, the page refreshes and the data is not caught, but it shows up in the URL. For example: https:/ ...