filter mongoose documents by objects within an array

Here is a mongoose schema that I have created:

var MySchema = new Schema({
    name: String,
    attributes: [ {name: String, value: Schema.Types.Mixed} ]
});

The challenge is that the clients will determine what the attributes will be, so it's unpredictable from the start.

I am working on developing a generic search function to filter results based on attribute.name='x', and potentially attribute.value='y' (although my example excludes values). Do you have any advice on how to approach writing such a method?

let filter = ['name', 'attributes.name=height', 'attributes.name=superpower'];

function search(filter) {
   //This  needs to be fixed
   const mongoReply =  await myModel.find({}, 'attributes.name');
}

UPDATE:

This code appears to be functioning correctly for me. I intend to conduct further tests to confirm its behavior as expected.

const mongoReply = await cuk.aggregate([
            {
                $match: {$and: [{'attributes.name' : 'color'}, {'attributes.name' : 'superpower'}]}
            },
            {
                $project: {
                    attributes: {
                        $filter: {
                            input: '$attributes',
                            as: 'attribute',
                            cond: {
                                $or : [ { $eq: [ '$$attribute.name', 'name'] },
                                    { $eq: [ '$$attribute.name', 'crypto_length'] }
                                ]
                            }
                        }
                    }
                }

            }
        ])

Answer №1

To execute the query properly, it should follow this structure:

await MyModel.find({ "attributes.name": "x", "attributes.value": "y" })
             .select(["attributes.name", "attributes.value"])

For more information on how to use the select method, refer to this link

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

Problem Encountered with Modifying Active Link Color in Next.js Following Introduction of Multiple Root Layouts

Currently, I am in the process of developing an application with Next.js and incorporating multiple root layouts from the official documentation at https://nextjs.org/docs/app/building-your-application/routing/creating-multiple-root-layouts. This was neces ...

I have a dynamic blog site that is generated on the fly using Ajax, making the content unsearchable

I have a blog website that is created dynamically using Ajax (XMLHttpRequest) and the HTML History API. One issue I am facing is that my content is not searchable by search engines like Googlebot. I know that Google is now able to analyze such sites, but w ...

Retrieving current element in AngularJS using jQuery

I have 4 templates, each with mouse actions that trigger functions: ng-mouseover="enableDragging()" ng-mouseleave="disableDragging()" Within these functions, I update scope variables and would like to add a class using jQuery without passing any paramete ...

When attempting to perform a second addition operation on the Angular calculator, it fails to work. However, each addition works perfectly when done individually

I have encountered a curious issue with my Angular calculators. Individually, they both function perfectly as intended. However, when I attempt to combine them, one always malfunctions. Is there something crucial that I am overlooking in this scenario? (D ...

Webpack automatically prepends "auto/" to script tags in the compiled HTML file

I am currently setting up an application for coding, but I am facing a problem with webpack. Every time I build the application, webpack automatically adds "auto/file.js" to the script tags instead of just "file.js". I have checked all my webpack configura ...

Implementing row updates using contenteditable feature in Vue.js

I am currently exploring how to detect and update the changes made in a 'contenteditable' element within a specific row. <tbody> <!-- Iterate through the list and retrieve each data --> <tr v-for="item in filteredList& ...

Remembering checkboxes labeled as arrays

Below is the code snippet I am working with: router.post('/expenseReport', ensureAuthenticated, async (req, res) => { try { const{ startDate, endDate } = req.body; var expenseArray = []; var count = 0; var ...

The .parents() method does not function properly when used with tables

I am attempting to display user details in a user list using AJAX JQuery, but it is not functioning as expected. It works for the first set of details within the same tr, but fails to work for the second detail in the td of the second row. How can I proper ...

Encountering an error while populating the Google Charts API with data: "The column header row need to be in array format."

Is there a way to populate a Google Chart with data from a function? I'm encountering an issue where I define the header row but receive an error message saying "Column header row must be an array." How can I resolve this problem? Below is the code sn ...

Tips for customizing the font color in Material UI Typography

Is it possible to change the color of only this text to red? return <Typography style={{ color: 'red' }}>Login Invalid</Typography> I came across this online solution, but I am unsure how to implement it as there is no theme={color ...

Unable to bring in openai on Node.js

I recently installed Node version 16.13.1 and globally installed the openai package using 'npm install -g openai'. In my script, I imported the necessary packages like this: const { Configuration, OpenAIApi } = require('openai') Howeve ...

Boost All Elements of Object Array Simultaneously with Mongoose Increment Method

I'm currently working on a project to track statistics on users (for a discord bot) like command usage and more. My goal is to store all this data in my mongodb. Essentially, I am aiming to regularly update the database with an array that records use ...

What is causing the button within my ExtJS grid to display as "[object Object]"?

Within an ExtJS grid, I am facing a scenario where I need to display a button in a specific column when the content of a cell meets certain criteria. To achieve this, I define the column with the button using a rendering function as shown below: { he ...

Unable to clear input field after submitting form in AngularJS with Ionic framework

Something strange is happening. Whenever I try to clear the model in the controller, the input field that is bound to the model using ng-model does not get cleared when the form is submitted. Controller angular.module('starter.controllers', []) ...

Deciding between Document.createElement() and Document.createTextNode() in Javascript

I'm currently exploring the distinctions between these two code snippets: // first one var h1 = document.createElement('h1'); var t = document.createTextNode('hello'); h1.appendChild(t); document.body.appendChild(h1); // second o ...

Create JavaScript variable from either HTML or database sources

Hello, I am trying to implement a counter that retrieves its value from a JavaScript file, but I would like to customize it. Below is the JavaScript code: function updateCounter(count) { var divisor = 100; var speed = Math.ceil(count / divisor); ...

Menu selection that changes dynamically based on radio button selection

Currently, I have four radio buttons and my goal is to have a drop-down menu change based on the selected radio button. Should I pre-write all the drop-down options and display them accordingly, or would it be better to use ajax to fetch the values from th ...

Avoiding Socket IO from timing out when the browser page is inactive or not the focused tab on Google Chrome, Mozilla Firefox, and Safari mobile browsers

I have developed a basic chat application using socket io. The functionality is quite similar to the socket io chat official demo. However, I am facing an issue where Socket io times out on all mobile browsers when the user minimizes the page, opens anothe ...

The Gulp task abruptly terminates before the Stream has a chance to trigger the "end" event

const gulpJasmine = require('gulp-jasmine'); const gulpDebug = require('gulp-debug'); function runTest(platform, testType) { const timer = startTimer(); console.log('started!'); return gulp.src('./src/**/_test/**/ ...

Encountering difficulty when determining the total cost in the shopping cart

I am currently working on a basic shopping cart application and I am facing an issue when users add multiple quantities of the same product. The total is not being calculated correctly. Here is my current logic: Data structure for Products, product = { ...