What is the best way to search for relational/nested schemas in mongoose?

I currently have two Mongoose schema models set up. Let's start with the GroupSchema model:

const GroupSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    admins: {
        type: String,
        default: ""
    },
    blocked: {
        type: String,
        default: ""
    },
    createdBy: {
        type: mongoose.Types.ObjectId,
        required: true,
        ref: 'user',
    },
    members: {
        type: String,
        default: ""
    },
    privacy: {
        type: String,
        required: true,
        enum: ['public', 'private', 'deleted'],
    },

})

Next, we have the GroupPostSchema model:

const GroupPostSchema = new mongoose.Schema({
    user: {
        type: mongoose.Types.ObjectId,
        required: true,
        ref: 'user',
    },
    text: {
        type: String,
        required: true
    },
    group: {
        type: mongoose.Types.ObjectId,
        required: true,
        ref: 'group',
    },
    image: {
        type: String
    }
})

When trying to execute a query like this:

var search = {
    "group.privacy": "public"
}

GroupPostSchema.find(search).exec((err, data) => {
    // handling the result here
})

The result is returning an empty array []. I came across a helpful answer on Stack Overflow regarding nested schema queries: Mongoose query for nested schema

However, I am looking to maintain GroupPostSchema.group as an Object rather than an Array. How can this be achieved in the simplest way possible?

Answer â„–1

Confirm using a different method instead of exec as shown below:

const members = await User.find({'group.privacy': 'public'});

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

Make an oblong shape from a circle by applying a transform in CSS or utilizing another efficient method

I am attempting to transform a circle into an obround using transform: scaleX(2), but it ends up becoming an ellipse instead. Increasing the width of the obround causes a jittery transition in my application. Is there a more efficient way to achieve this t ...

"Using the map function in Javascript to iterate through an array and then implementing

I am working on a script that involves an array of the alphabet along with two sets of values. The goal is to determine if a given value falls within the range specified by these two values and then print out the corresponding letter from the alphabet. H ...

At what point was the server's listener attached to the request in Node.js?

let http = require("http"); http.createServer(function(req, res) { req.addListener("data", function(dataChunk) { // some custom code here }); req.addListener("end", function() { // more custom code here }); }).listen(8888) ...

Generating a JSON array from a C# collection can be achieved by utilizing the System.Web.Script.Serialization

Can someone help me with this code snippet? var httpWebRequestAuthentication = (HttpWebRequest)WebRequest.Create("http://api"); httpWebRequestAuthentication.ContentType = "application/json"; httpWebRequestAuthentication.Accept ...

Mongoose: Eliminating deeply embedded subdocuments within an array

As I embark on my first real project, I am facing challenges in handling nested subdocuments in Mongoose. What is the most effective approach for deleting subdocuments that are nested multiple times without knowing the exact index of the array? For examp ...

Multiple button clicks causing events to fire repeatedly

My PHP file echoes a button, but when I click it, the action fires multiple times. Why is it behaving like this? I have tried solutions from Stack Overflow, but none of them seem to work. Any suggestions or corrections? $(document).on('click',& ...

Attempting to insert an element after the .load event has been triggered

I have been attempting to update the contents of ".myShop" after it's loaded from an external XML file, but without success. I believe my timing is correct, but I suspect that a loaded element may not be part of the DOM? Here's what I'm exp ...

Is it more efficient to declare a variable or directly return the variable from the Element's getText() promise in Protractor?

I am facing a scenario where I need to retrieve the text of a web element using a promise and then extract a specific part of the string for further processing. Which example, the one at the top or the bottom, should I use? var id = element(by.binding( ...

Regular Expression: do not include comments that are placed inside quotation marks

Using the regular expression /#(.*?)\r?\n|#(.*?)$/g, I was able to parse the following content. However, it also matches the comment within the quotes. How can I prevent this from happening? # # this is a comment # but this is '# not a c ...

Flutter - Unhandled Exception: NoSuchMethodError: Attempting to access the getter 'filename' on a null object

I am currently learning Flutter and encountering issues in my project, specifically related to the error mentioned in the title. My goal is to upload files in Flutter using Dio and FormData. The "img[]" variable represents data from a MongoDB database, and ...

Attempting to fetch particular information from the mongodb database, however, the console is displaying an 'undefined'

app.get("/admin/:id",isLoggedAdmin,function(req,res){ Advocate.findById(req.params.id, function(err,advocateFound){ if(err){ console.log(err); } else{ Advocatecase.find({uid:advocateFound.uid},function(err,allcase ...

Using Vue.js, is it possible to apply a class to a clicked element and then remove it when another element is clicked?

While developing an app using Vue.js, I have run into an issue. I am familiar with how to solve this problem using jQuery, but I am struggling to find a solution within my Vue app. Let me explain quickly - I have a list of items and I want to assign a spec ...

The AngularJs Wizard Validation Inputfield is unable to locate the scope

Hello all, I am new to AngularJs and encountering an issue with my code. Currently, my HTML structure looks like this: <div class="wizardContainer"> <wizard on-finish="finishedWizard()"> <wz-step title="1"> <h1>Questio ...

Material UI button text not receiving props

Within my application, I have a situation where I utilize data attributes on buttons to gather specific contextual information in the modal that is triggered by clicking the button. This functionality depends on accessing the data attributes through e.targ ...

How does a web crawler determine which elements to click on when navigating a webpage?

Recently, I developed a crawler application that is able to access a given webpage and extract the HTTP Requests before storing them in an excel sheet. Currently, I have implemented click events for some buttons using jQuery. Now, I am faced with the chal ...

Leverage recursion for code optimization

I'm currently working on optimizing a function that retrieves JSON data stored in localStorage using dot notation. The get() function provided below is functional, but it feels verbose and limited in its current state. I believe there's room for ...

Validation of hidden fields in MVC architectureUsing the MVC pattern to

Depending on the selections made in the dropdown menu, certain fields will appear and disappear on the page. For example: <section> @Html.LabelFor(model => model.AuctionTypeId) <div> @Html.DropDownList("AuctionTypeI ...

What is the best way to create a self-referencing <div> in HTML?

After extensive research, I turn to seeking advice and guidance on Stack Exchange. I have a seemingly straightforward goal in mind. I want to create a <div> id/class that will automatically generate a link to itself using scripting of some sort. Be ...

Draggable resizing of the Accordion component in React.js using Material-UI

In the visual representation, there are two Accordions—one positioned on the left (30%) and the other on the right (70%). Upon clicking the button, the right accordion disappears, while the one on the left expands to cover the full width (100%). A featu ...

Modify the text tone within a specific cell

Welcome to my unique webpage where I have implemented a special feature. The text highlighted in red represents the unique identifier for each individual cell. Interestingly, below there is an input field containing the code "0099CC", which corresponds to ...