Tips for utilizing the find function with nested documents in MongoDB in conjunction with Next.js?

I have structured my data in such a way that it is obtained from

localhost:3000/api/notes/[noteTitle]/note2

{
  "data": [
      {
          "_id": "62ff418fa4adfb3a957a2847",
          "title": "first-note2",
          "note": { "_id": "62ff399da4adfb3a957a2808", "title": "first" },
      },
      {
          "_id": "631af43b054a6aef1a7c4f08",
          "title": "first-note22",
          "note": { "_id": "62ff399da4adfb3a957a2808", "title": "first" },
      },
      {
          "_id": "631af504054a6aef1a7c4f11",
          "title": "second-note22",
          "note": { "_id": "62ff3a10a4adfb3a957a2817", "title": "second" },
      }
  ]
}

Upon sending an API request to

localhost:3000/api/notes/first/note2
, I aim to retrieve only the data with the title "first" in the note object.

This is how I attempted to accomplish this on the API pages:

export default async (req, res) => {
  const { query: { noteTitle }, method } = req;

  switch (method) {
    case "GET":
      try {
        const notes = await Note2.find({"note.title": noteTitle}).populate("note");
        res.status(200).json({ success: true, data: notes });
      } catch (error) {
        console.log(error);
      }
      break;

    default:
      res.status(400).json({ success: false });
      break;
  }
};

However, I am receiving an array of entries instead of the expected two matches. What could be the issue?

Edit: Here is my Note2 schema:

const Note2Schema = new mongoose.Schema({
  title: { type: String, unique: true },
  note: { type: mongoose.Schema.Types.ObjectId, ref: "Note" },
});
module.exports = mongoose.models.Note2 || mongoose.model("Note2", Note2Schema);

And this is my Note Schema:

const NoteSchema = new mongoose.Schema({
  title: { type: String, unique: true }
});
module.exports = mongoose.models.Note || mongoose.model("Note", NoteSchema);

Edit 2: After referring to the mongoose documentation, it appears that populating and filtering based on populated data may not yield the desired results.

Is there a workaround solution for achieving what I intend to do?

Typically, populate() does not support filtering based on properties of the referenced data. For instance, the following query will not return any results even when author is populated.

const story = await Story.
  findOne({ 'author.name': 'Ian Fleming' }).
  populate('author').
  exec();
story; // null

Answer №1

"note" acts as a property within the array called "data". Therefore, your query needs to follow this syntax -

const notes = await Note2.find({"data.note.title": noteTitle}).populate("note");

Answer №2

After consulting the mongoose documentation, I discovered that it is not possible to use populate() to filter notes based on the properties of note2's title.

const notes = await Note2.find({ })
  .populate({
    path: 'note',
    match: { title: noteTitle },
  })
  .exec();

My objective was to retrieve only the data that contains the string "first" in the note.title. To achieve this, I devised a workaround solution by applying a second filter after fetching all Note2 data from the database.

const notes = await Note2.find({}).populate({ path: "note" })

const selectedNote2 = notes.map((singleNote) => {
  if (singleNote.note.title === noteTitle) {
    return singleNote
  }
  return []
})

res.status(200).json({ success: true, data: selectedNote2});

I am unsure if there exists a more optimal solution than the one I have implemented here.

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

Having issues with socket.io connectivity on my Node server

I am setting up my node server to update all connected clients with real-time information. However, when I run the code provided below, the io.sockets.on('connection') callback keeps firing constantly, flooding the console with the message Client ...

Filtering nested object properties by value using Java Script

I am seeking assistance in filtering nested Objects by property values, with a specific requirement involving values stored in an array. Despite previous similar inquiries, I have yet to find a solution tailored to cases like mine. In reviewing the code s ...

Preventing Error in D3 Updates Caused by Invalid Path Formats

I'm encountering a problem with the d3 tree layout while dynamically adding nodes. When I add a path symbol to the node based on its type, I receive an error message "invalid path format" during updates. Both the Enter and update methods utilize the ...

Navigating the dynamic routing features in Next.js 13: excluding specific components

I'm currently developing an application using Next.js version 13. Within my app directory, I have various components implemented. In Next.js, the routing system is based on the file structure. For instance, if there's a file named app/MenuItem/ ...

Using JavaScript to print radio type buttons

Currently working on a web page and I've encountered a problem that's got me stumped. There are two sets of radio buttons - the first set for package dimensions and the second set for weight. The values from these buttons are assigned to variable ...

Issue with inserting dictionary object containing nested array into MongoDB using pymongo

I am attempting to insert dictionary objects into MongoDB using this Python script: result = centros.insert(clinica) where 'clinica' is the dictionary object being inserted. The first set of data provided below is successful: { 'Genera ...

The router is displaying the component directly on the current page rather than opening it on a separate page

The issue is that the router is rendering the page on the same page instead of generating a new one. When clicking on the Polls link, it only renders the page there but the URL changes in the browser. Polls.js import React from 'react'; import ...

Scraping data from the web using R and creating interactive plots with hover text in Plotly without

I'm attempting to extract hover text content from plotly traces that have been shared online. This is a new type of scraping for me, and I'm exploring ways to accomplish this task in R without relying on selenium or phantomjs, possibly with the u ...

What is the best way to retrieve the innerHTML content of an anchor tag with Cheerio?

Looking to extract data from an HTML page, a simplified example is provided below. Upon running the code, I anticipate the output to be [ "foo", "baz", "quux", ] but instead encounter an error message stating "TypeError: anch ...

There was a glitch encountered while constructing (Verifying type validity) with Prisma

There was an issue in the node_modules/@prisma/client/runtime/library.d.ts file on line 1161, specifically error TS1005 where a '?' was expected. 1161 | select: infer S extends object; | ^ 1162 | } & R ...

What is the best source for retrieving data - my database, an open api, or JSON files?

For my novice portfolio, I am creating a Pokemon team builder app. With over 800 unique Pokemon to choose from, each with its own abilities and moves, the project requires substantial data. Luckily, there is a free online api known as PokeAPI that provides ...

Extract string data from JSON payload

How can I extract the itemlocation from itemInfo and display it in a new column in my react table using Material UI? While I know this can be done on the backend, I am looking for a way to achieve this without backend involvement. Below is an example of ho ...

There are various iterations of html2canvas available

After upgrading html2canvas from v0.5.0 to v1.0.0, a specific function ceased to work on iOS. Therefore, I am interested in utilizing v0.5.0 on iOS and v1.0.0 on other devices. Is there a way to incorporate and switch between both versions of html2canvas ...

Rotate each row of the table in sequence with a pause between each flip

I have a table with 3 columns and 10 rows. I would like to flip each row one by one, where each row contains data on both the front and back sides. The flipping animation should be similar to the example provided in this link, but the flipping should sta ...

Error message encountered in Next.js when trying to import 'SWRConfig' from 'swr': ClerkProvider Error. The import is not successful as 'SWRConfig' is not exported from 'swr

I recently started working on a new Next.js project and integrated Clerk into it. I set up the env.local and middleware.ts files before wrapping the HTML div with ClerkProvider. However, when attempting to run the project locally, I encountered the followi ...

Dealing with undefined URL errors

My frontend log is crowded with these errors. Whenever I visit an undefined address, my terminal in VSCode displays the following error messages. The real issue is that I am unsure how to effectively manage errors arising from hitting an undefined URL. For ...

How come my dynamic source path doesn't function correctly unless I add an empty string at the end of it?

Recently, I encountered an issue while using Vue.js to dynamically create a source attribute using an object's properties. Here is the code snippet where I faced the problem: <img :src='"../assets/" + project.image.name + "." + project.image. ...

I'm having trouble loading my Google Maps widget. Everything was functioning flawlessly until I attempted to hide it using the .hide function

After successfully implementing a Google Maps widget, I encountered an issue when trying to toggle its visibility using jQuery. Despite clicking on a div element to reveal the widget, the map fails to load inside the designated container. It seems as tho ...

Struggling with properly navigating a JSON file in my JavaScript code... specifically trying to access and retrieve the "responseObject.weather[i].weatherresponseObject.weather[i].description" data

Struggling with extracting data from a PHP file in JSON format to display on an HTML file using JavaScript. I seem to be encountering issues with accessing responseObject.weather[i].weatherresponseObject.weather[i].description, and I suspect it might be d ...

Securing uploaded documents and limiting access to approved individuals

Currently, I am utilizing Multer for file uploads and I am contemplating the ideal approach to secure access to these files post-upload. In my system, there are two user roles: admin and regular user. Users can only upload photos while only admins have ac ...