Using the Mongoose $or operator with a nested array in query conditions

Here are the schemas I am using:

//ProjectModel
const ProjectSchema: Schema = new Schema(
 owner: { type: Schema.Types.ObjectId, ref: "User" },
 users: [{type: Schema.Types.ObjectId, ref: "ProjectUser", unique: true }]
);

//Project User model
const ProjectUserSchema = new Schema(
  {
    user: { type: Schema.Types.ObjectId, ref: "User", require: true },
    role: {
      type: String,
      default: 'basic',
      enum: ["basic", "projectuser", "moderator", "admin"]
    },
    project: { type: Schema.Types.ObjectId, ref: "Project", require: true },
  },
  {
    timestamps: true,
    usePushEach: true,
  }
);

The User model contains fields such as password and name.

I am attempting to locate a User within a ProjectModel either as the owner (UserSchema) or among the users (ProjectUserSchema)

ProjectModel.findOne()
                    .or([{ owner: req.params.user }, { "users.user": req.params.user }])
                    .then(project => {
                        res.json(project);
                    });

However, this query is returning null. Even trying the condition

.or([{ owner: req.params.user }, { "users._id": "PROJECT USER ID" }])
does not yield results.

What steps should I take next?

Answer №1

If you want to handle the incoming req.params.user as an ObjectId, you can perform a conversion. Below is an example of how you can achieve this:

const mongoose = require('mongoose');

const getProjectByUser = (req, res) => {
  let userId = mongoose.Types.ObjectId(req.params.user);

  ProjectModel
    .findOne({
      $or: [
        { "owner": userId },
        { "users": userId }
      ]
    })
    .then(project => {
      res.json(project);
    })
    .catch(e => {
      res.json({ error: "An error occurred!" });
    });
}

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

Ways to display multiple PHP pages in a single division

Within my project, I have a unique setup involving three distinct PHP pages. The first file contains two divisions - one for hyperlinked URLs and the other for displaying the output of the clicked URL. Here is an excerpt from the code snippet: <script& ...

Programmatically setting properties for elements

I have a question about how to programmatically add a prop to a component in my React project. Here is the scenario: In the render() method, I have the following code snippet: <TextField name="password" va ...

Steps to trigger a Bootstrap modal when the user clicks anywhere on the webpage

I need assistance with setting up a Bootstrap dialogue modal to open at the clicked position on a mousedown event when a user interacts with the page. Despite my attempts, the dialogue modal is not opening where it should be. Here's what I've tri ...

Exploring Jasmine's Powerful Spying and Mocking Capabilities in JavaScript Prototypes

Hey everyone, I need some help with a JavaScript issue. So, I have a file named FileA.js which contains a prototype called FileAObject.prototype along with a function named funcAlpha(). Here's a snippet of what it looks like: File = FileA function s ...

[filepond] in order to enroll using the serverId value received from the server

Using 'filepond' within a Vue application is causing an issue. In the "process" function, the ID value obtained after transferring the file to the server (response.id) needs to be registered as 'serverId' of the file. Upon checking the ...

Using Jquery's getJson method, we can easily fetch and retrieve the appropriate JSON string by

I have the following code snippet at the beginning of the JSON url: if(isset($_GET['template']) && $_GET['template']=="blue") { $inifile_path="ctr/subthemes/blue/"; } else { $inifile_path="ctr/subthemes/fresh-n-clean/"; } Addi ...

Run several asynchronous HTTP requests in the background within a Chrome extension

I am facing a situation where I need to make multiple ajax requests through a Chrome extension and display the successful results in the popup HTML of the extension. I have created an array of URLs and loop through them to perform the ajax requests. Every ...

Tips for troubleshooting a node module that is part of a build process

When working on my applications, I often rely on the NPM package.json to handle my build tools. However, I've come across a module that seems to have a bug. I'm eager to debug it, but I'm unsure how to do so within the context of the build t ...

ReactJS does not trigger a re-render when changes are made to CSS

I'm curious about the reason why ReactJS does not automatically reapply CSS to child components even when componentDidUpdate() is called. I conducted a small demo where adding a new box doesn't change the color of existing boxes, even though the ...

Having all elements at the same height

I am looking to enhance my JavaScript code to only impact 4 items at a time. The goal is to target the first 4 instances of .prodbox, adjust their height accordingly, then move on to the next set of 4 and repeat the process. This sequential adjustment will ...

What is the best way to access a cached value?

I am currently utilizing the node-cache-manager library to manage caching in my Node.js application. After successfully adding an item to the cache using the following code: import cacheManager from 'cache-manager'; const memoryCache = cacheMan ...

Detach an item from its parent once it has been added to an array

Currently, I am facing an issue with a form on my blog. The blog is represented as an object that contains multiple content objects within it. I seem to be experiencing some confusion because the reactivity of the content I add to the Array persists with t ...

Utilizing Typescript for parsing large JSON files

I have encountered an issue while trying to parse/process a large 25 MB JSON file using Typescript. It seems that the code I have written is taking too long (and sometimes even timing out). I am not sure why this is happening or if there is a more efficien ...

Achieve maximum height with background images

Having trouble with responsiveness on my box containing a background image. I am aiming for the box to adjust its height based on the background image, as I have set the background-size attribute to auto. html: <div class="index_boxs" id="discover_win ...

Is it possible to alter the name of a slot before displaying the element in the shadowDOM, depending on the slot utilized in the DOM?

In my project, I am working on implementing different features for both desktop and mobile devices. Some of these features can be replaced by slots. My goal is to have a slot that can be either replaced by a desktop slot called poster-foreground, or a mobi ...

Retrieving Public ID from Cloudinary Link

I have a NodeJS project where I am using Cloudinary to host my media on the cloud. In order to delete an image from the Clodinary Cloud, I need to provide the Public Id for that image to the Cloudinary API. I have noticed that the Public ID is embedded in ...

Searching dynamically using class names with JQuery

I am seeking to create a dynamic search input based on the class names within the span tags. However, I am struggling with displaying the class name that I have identified. My goal is to show the class names that match the entered value in the input on the ...

Mastering the Art of Live Search in Drop Down Multi Select

I need to develop a search functionality similar to the one found on . This search should allow users to select options from a dropdown menu or type their own search query, and provide live search results. I attempted to use the jQuery plugin https://www.j ...

Is it possible to switch the summernote editor between airmode and toolbar mode?

Currently, I am working on creating a report editor that displays only one toolbar when multiple summernote WYSIWYG editor sections are used. My solution involves having the first section as a full editor and the other section in airmode. Below is the HTM ...

What steps should I take to delete a class from my calendar after it has reached the maximum capacity of 20

I am trying to create a feature that automatically removes a class from the calendar if more than 20 people have booked it. On the admin side of the system, I can add classes to the database but need help implementing this check. Below is my current code ...