Searching in mongoose using nested objects

It's possible that this question is a duplicate, but I haven't found a suitable answer to my issue yet.

Currently, I have an ExpressJS server set up to handle API requests for fetching data from a MongoDB database. My database connection is made using mongoosejs for querying and saving data.

I'm working on a route that should retrieve all data matching some user input, but I'm facing difficulties with the query itself. Despite extensive research online, I haven't been able to find a similar problem.

Below, I'll provide an example of the code I currently have:

Route Code

// -- Return matched data (GET)
router.get('/match', async (req, res) => {

    const style_data = req.query.style; // Get URL param for style scores ** Comes in as a string **
    const character_data = req.query.character; // Get URL param for character scores ** Comes in as a string **

    // Run match systems
    const style_matches = style_match(style_data);

    res.send({
        response: 200,
        data: style_matches
    }); // Return data

});

Query Code

// ---(Build the finder)
const fetch_matches_using = async function(body, richness, smoke, sweetness) {
    return await WhiskyModel.find({
        'attributes.body': body,
        'attributes.richness': richness,
        'attributes.smoke': smoke,
        'attributes.sweetness': sweetness
    });
}

// ---(Start match function)---

const style_match = async function (scores_as_string) {

    // ---(Extract Data)---
    const body = scores_as_string[0];
    const richness = scores_as_string[1];
    const smoke = scores_as_string[2];
    const sweetness = scores_as_string[3];

    const matched = [];

    // ---(Initialize Variables)---
    let match_count = matched.length;

    let first_run; // -> Exact matches
    let second_run; // -> +- 1
    let third_run; // -> +- 2
    let fourth_run; // -> +- 3

    // ---(Begin DB Find Loop)---

    first_run = fetch_matches_using(body, richness, smoke, sweetness).then((result) => {return result});

    matched.push(first_run);

    // ---(Return Final Data)---
    
    return matched

}

Example of DB Object

{
 _id: mongoid,
 meta-data: {
  pagemd:{some data},
  name: whiskyname
  age: whiskyage,
  price: price
 },
 attributes: {
  body: "3",
  richness: "3",
  smoke: "0",
  sweetness: "3",
  some other data ...
 }
}

When I make a request to the route in Postman, the JSON data appears as follows:

{
response: 200,
data: {}
}

Additionally, when I use console.log() to check the output of matched within the style match function after pushing it, I get [ Promise(pending) ], which confuses me.

If I log the result within .then(), I receive an empty array.

I attempted using the populate() method post finding, which does work technically, but instead of returning only matching data, it brings back every entry in the collection. I believe I may be making a mistake here, but I also don't see why I would need to utilize the .populate() function to access the nested object.

Is there something fundamentally incorrect in my implementation?

Furthermore, it's worth mentioning that the route and matching functions are stored in separate files for simplicity's sake.

Thank you in advance for any insights provided.

Answer №1

Just wanted to share an update as I was able to resolve the issue at hand.

The problem stemmed from my use of the .find() function, where I needed to specify the items to search by and also include a callback function to handle errors and data retrieval. Here is the updated code snippet:

Updated function

const fetch_matches_using = async function(body, richness, smoke, sweetness) {
    const data = await WhiskyModel.find({
        'attributes.body': body,
        'attributes.richness': richness,
        'attributes.smoke': smoke,
        'attributes.sweetness': sweetness
    }, (error, data) => { // updated ¬
        if (error) { 
            return error;
        }

        if (data) {
            console.log(data)
            return data
        }
    });

    return data; // updated
}

I'm still encountering an issue with sending the retrieved results back to the route, but I suspect it's a separate concern. If it turns out to be related, I'll make sure to update this response with the solution for that as well.

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

Creating a tree structure in JavaScript by parsing a collection of URLs

Hello everyone, I am currently working on creating a dynamic menu list that allows users to create elements without any depth limitations. THE ISSUE The structure of my URLs is as follows: var json_data = [ { "title" : "Food", "path" ...

Error: No targets with the name "taskname" were found for the custom Grunt task

Just recently, I decided to create my own custom task and here's the process: Started by making an empty folder named "custom-tasks" in the Document Root Next, I created the actual task file: "mytask.js" Implemented the functionality required for th ...

I am required to deliver a certificate to a secure HTTPS web address

I need to utilize a third-party API that necessitates sending a signed HTTPS request from my NodeJS express web server. The process involves using a specific certificate provided by the API. Unfortunately, I am facing some challenges with this integration ...

Sift through JavaScript problems

My goal is to implement a filtering function on my input that will display a different result. However, I have encountered an issue where the this.data.stationInfo.stations array is being changed, as shown in the console.log output. According to the Mozil ...

Utilizing Vue.js to connect with a Node.js server

After setting up a basic Node.js server, the following code is running successfully: var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'content ...

Get data from ajax request in controller

I'm currently working with this JavaScript code snippet: var formData = new FormData($('#formSlip').get(0)); formData.append('myList', JSON.stringify(tests)); The variable tests holds a list of objects. I am making an AJAX PO ...

Page is restricted to uploading only a single image at a time

I'm currently working on setting up a simple server that can handle both POST and GET requests. The goal is to allow users to upload images to a directory while saving relevant data like date, name, description, and id to a JSON file. In the case of a ...

Refreshing the page allows Socket.io to establish multiple connections

I've been working on setting up a chatroom, but I've noticed that each time the page refreshes, more connections are being established. It's interesting because initially only one connection is created when I visit the chat room page. Howeve ...

Click on the image to prompt the file upload dialog box to open

Is it possible to open the image upload file dialogue box when clicking the button tag? If so, how can I achieve this using PHP? while{ echo "<td><button><img src='".$cfet['productimage']."' width=&apos ...

Deciphering the meaning of the 'this' keyword in a prototype function of an object

var Controller = function () { try { throw new this.userException('test', 'test'); } catch (error) { if (error instanceof this.userException) { console.error(error.stack); } } } Controller.prototype.userExceptio ...

Tips for automatically setting tabulator columns for unknown JSON data

I am a novice developer and have come across a Json object whose contents I am not familiar with, which I need to incorporate into Tabulator. In order to do so, I must provide details for each column. For example: var JSONData =[{A:12,B:3,C:13},{A:5,B:23 ...

secure user authentication using express and sockjs

Is there a resource that explains methods for authenticating users in SockJS without using cookies? Ideally, the information should include examples. I prefer not to use Socket.IO. ...

WebDriver is now being permitted by Chrome to access insecure pages

When using Chrome 62, Chrome Driver 2.33, and WebDriver 3.6.0, I have noticed that Chrome allows pages to load with bad SSL certificates. Even though the URL bar displays "Not Secure," the page still loads without any issues. Strangely, if I navigate to th ...

What is the reason behind the lack of asynchronous functionality in the mongoose find method

Outdated code utilizing promises I have some legacy code implemented with mongoose that retrieves data from the database. The schema being accessed is AccountViewPermission. Everything works fine as I am using a .then, which essentially turns it into a Pr ...

Vue failing to update when a computed prop changes

As I work with the Vue composition API in one of my components, I encountered an issue where a component doesn't display the correct rendered value when a computed property changes. Strangely, when I directly pass the prop to the component's rend ...

Determine whether any element in the array matches a property of the object

Let's start with an array: arr=[ "EMPRESA", "CD_DIRECAO", "DT_INI_DIRECAO" ] Next, we have an object: primary = { "EMPRESA": {"type": "varchar"}, "CD_DIRECAO": {"type": "varchar"}, "DT_INI_DIR ...

Excessive CPU Usage in Meteor.js

An application built on meteor.js version 0.82 is currently being hosted on an Ubuntu 14.04 server equipped with 2GB of memory and 2 CPU cores. The deployment was done using the mup tool. Despite this setup, the CPU usage is unusually high, as indicated by ...

To use the req.flash() method in Node.js with Express, you must have

I'm having issues with implementing connect-flash. Here is the setup in my code: var flash=require('connect-flash'); var session=require('express-session'); app.use(flash()); app.use(session({ secret:settings.cookieSecr ...

What is the best way to search for a specific item in Express.js?

I recently got the Leaderboard API issue fixed, but now I'm encountering a new problem with express Querying. Specifically, I'm attempting to search for a specific Discord ID using quick.db as my database. I've included an excerpt of my expr ...

Find one record for each unique serial number in MongoDB

There are four documents in my possession, each bearing a unique serial number. My objective is to retrieve the final document associated with each serial number. For instance. Collect Name:Sales Serial name date 10000 A 2014 10000 B 2015 ...