How to access related data using find()?

Hey, guys,
I’m trying to look up information in a related document. I have this structure:

{
        "_id": "61e16e1edf2e211c5098852f",
        "data1": "xxx",
        "data2": "xxx",
        "data3": "xxx",
        "access": {
            "_id": "61e16e1edf2e211c5098852d",
            "data4": "xxx",
},

I declared the model like this:

const mongoose = require("mongoose");

const Requests = mongoose.model(
  "Requests",
  new mongoose.Schema({
    data1: String,
    data2: String,
    data3: String,
    access: 
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Access"
      }
    
  })
);

module.exports = Requests;

I need to do two filters, the first one searches using “data1” OR the second one using “data4”

I did this method, but I have difficulties accessing the data4. How do I access the data4?

exports.filter = async (req, res) => {
	const query = {};
	var data = req.body;

	if (data.data1) {
		query.data1 = data.data1;
	}

	if (data.data4) {
		query.data4 = data.data4;
	}

	const sol = await Requests.find(query).populate("access");
	res.send(sol);

}

When I send data in “data4” I get [] even though I have results. I appreciate if anyone can help me analyze it.

Hi @Edrian_Biagi ,

The data4 seems to be under access and not on root level.

It feels like the query object should be :

query["access"].data4 = data.data4;

Thanks
Pavel

Thanks for the feedback. I tried your solution, but to no avail!

query[“access”].data4 = data.data4;

TypeError: Cannot set properties of undefined (setting ‘data4’)

Hi @Edrian_Biagi ,

My suggestion was kind of a pseudo code.

What I mean is that the query document should look like:

{ 
"access.data4" : <VALUE>
...
}

So the entry should be named “accass.data4”…

I think that the correct code is

query["access.data4"] = data.data4

Thanks
Pavel

I did the test, but I got an empty result [], even with a value that is in the bank!

Wait you are confusing me in this case the data4 is on a root level and not under access…

Or is it just an input for http endpoint, what is the actual query code?

In the image, I show how I’m using the “GET” method in the postman, to perform the query using “data4”.

The data4 is declared as I mentioned in the question. It is in the “Access” schema and I relate it to “Requests”