What is the best way to locate records by the parameter's ID from a separate collection?

var CartSchema = new Schema ({
    productId: {type: Schema.Types.ObjectId, ref: "M_Data_Product", default: null},
    qty: {type: Number, default: 0},
    price: {type: Float, default: 0},
});

This is my shopping cart model.

var ProductSchema = new Schema({
    name: {type: String, default: null},
    categoryId: {type: Schema.Types.ObjectId, ref: "M_Data_Category", default: null}
});

This is the Product model I have created.

I am looking to retrieve cart records based on a specific categoryId. Any suggestions on how to achieve this?

Answer №1

Searching and linking data using Model.aggregate() method in MongoDB:

Model.aggregate([
  {
    "$lookup": {
 "from": "Product", //collection name of product
 "localField": "productId",
 "foreignField": "_id",
 "as": "product"
}
  },
  {
    $match:{"product.categoryId":"exampleId"}
  }
])

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

Vuejs Countdown Timer Powered by Moment.js

Currently, I am working on a vuejs page and I am looking to incorporate a countdown timer that counts down from 5 minutes (e.g. 5:00, 4:59, and so on). Although I have never used momentjs before, I have gone through the moment docs but I am finding it ch ...

Creating a Rest API URL in Vue.js by extracting form values

I just finished coding this Vue component: <template> <div> <h2>Search User By ID</h2> <input v-model="userId" type="number" placeholder="modify me" /> <br /> <p v-if="userId.length != 0"> ...

Utilizing npm packages from third-party sources within a custom extension for personal use (not intended for distribution)

Exploring the idea of developing a basic Firefox extension that involves external modules such as Firebase and Cheerio, but there doesn't seem to be much information available on this topic. I noticed there are legacy options like jpm, but they'r ...

Keep track of numerous clicks and gather all values in a single line

I have a scenario where I need to fetch values from multiple buttons on my webpage and display them together in one line. How can this be achieved? There are 3 buttons, each returning a specific value when clicked: Dark : scoop Danger : swoosh Warning ...

iPhone: Fixed position div disappearing

Currently, I am working on creating a mobile menu for my Joomla 3 site located at . The menu is functioning correctly on desktops, however, when attempting to view it on my iPhone, the menu slides in but remains invisible. Despite this, I can still tap on ...

Launching an external software using electron

I am in the process of developing my own personalized Electron app for managing other applications on my device. One issue I have encountered is the inability to create a link that opens my own .exe applications. I have attempted various methods without su ...

Adjust the size of the div to match its parent's size when resizing

Can a div be resized to match its parent's size on window resize? Here is the current HTML code: <div class="sliderContainer"> <div id="cyler"> <div class="cy1" style="background-image:url(images/Keggy_Banner_Ie.jpg); back ...

working with CSV files in JavaScript using AngularJS

Currently, I am working on building a simple angular application that can parse CSV input and populate a table with the extracted data. If you're curious about what I'm trying to accomplish, feel free to check out this Plunker demo - http://plnk ...

Issue: Cannot access the 'map' property of an undefined value in a React Mongo DB error

My React code was running perfectly fine until I encountered an error message in the browser console: "TypeError: Cannot read property 'map' of undefined". Let me share the snippet of my code with you. const MyComponent = () => { const [dat ...

(Express) Passing data between functions within express.Router().get

What is the best way to transfer a value from one function to another within a router.get method? router.get('/someurl', (req, res, next) => { const token = req.headers.authorization.split(' ')[1] //jwtToken const jwt = jwt.verify( ...

Error Notification in React Bootstrap - Stay Informed!

When a 401 error is returned from the API, I need to show an error message in the component. My approach involves using an unbound state and ES6. However, I encountered this error: Cannot read property 'setState' of undefined Below is the login ...

Retrieving time zone using offset with javascript

I am looking for a way to schedule time-based events on my server operating in UTC time. For the user interface, I need to input 2 parameters: The local time when the scheduled event should trigger The timezone offset Instead of displaying timezone n ...

Node.js Promise function halting execution prior to returning

How can we adjust the code provided below to allow the getUser(theToken) promise function to successfully return its internally generated valid value without freezing? app.get('/auth/provider/callback', function(req, res) { var queryData = u ...

Pass data between JavaScript and PHP using the Phaser framework

I am trying to pass a JavaScript variable to PHP and then store it in a database. Despite searching for solutions on Google, I have not been successful. Most suggestions involve using AJAX, but the code doesn't seem to work when I try it. I attempted ...

Running Applications with React Using Command Line Interface (CMD)

I'm currently working on creating a .cmd file to handle the installation of dependencies and then execute my React application. Following some research, I have come up with the following code snippet inside my .cmd file: @echo off npm install pause np ...

Using the array.prototype.map method on props in React.js results in an array that is devoid

Recently, I've started exploring the world of React and encountered a problem while attempting to convert the value of props into a JSX element using array.prototype.map(). You can learn more about this method at this link. Here is a snippet of a Rea ...

Are there advantages to incorporating d3.js through npm in an Angular 2 TypeScript project?

Summary: It is recommended to install d3.js via npm along with the typings. The accepted answer provides more details on this issue. This question was asked during my initial stages of learning Angular. The npm process is commonly used for tree-shaking, pa ...

Navigation bar transforms color once a specific scroll position is reached

My website features a sleek navbar fixed to the top of the window. As users scroll past a specific div, the background color of the navbar changes seamlessly. This functionality has been working flawlessly for me thus far. However, upon adding anchor link ...

Is there a way to determine the orientation of an image in React-Native, whether it is horizontal or vertical

When working with react-native, I aim to utilize the 'contain' feature for vertical images and the 'stretch' feature for horizontal images. What would be the best way to determine the orientation of an image as either horizontal or vert ...

What is the best way to retrieve a single document from MongoDB by using the URL ID parameter in JavaScript?

I'm currently working on a movie app project and have defined my movie Schema as follows: const movieSchema = new mongoose.Schema({ name: { type: String, required: true }, genre: { type: String, required: tr ...