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

Error occurred due to an invalid element type with the imported React component

Using a component imported from an npm package in two different apps has resulted in unexpected behavior. In one app, the component functions perfectly as expected. However, in the other app, an error is raised: Element type is invalid: expected a string ...

Steps for adding a row as the penultimate row in a table

There aren't many solutions out there that don't rely on jQuery, but I'm looking to avoid it. The row content needs to be generated dynamically. Here is my flawed approach: function addRow() { let newRow = '<tr><td>B ...

How can you use React.js to only display "Loading..." on the page while the full name is included in the URL?

I've hit a roadblock while trying to solve this issue. Here's the situation: On the page where I need to display certain information, I intended to showcase the full name of the individual from a previous form submission. However, instead of seei ...

Can two Angular element components be utilized simultaneously on a single page in Angular 6?

Currently, I'm attempting to host independent Angular elements that can be seamlessly integrated into a non-Angular webpage. Everything works perfectly fine when there's only one element on the page, but as soon as I try to load two or more, I en ...

Organize an array based on its ratio

I am attempting to organize an array based on the win and lose ratio of each player. This is how my code currently looks: const array = [{playerName: 'toto', win: 2, lose: 2}, {playerName: 'titi', win: 0, lose: 0}, {playerName: &apo ...

Empty body detected in Jquery AJAX request with Django REST running in a Docker environment

Using JavaScript to load a template called index.html from the /static directory. The JavaScript code in app.js: var obj = new Object(); obj.startTime = "123"; obj.endTime = "456"; console.log("fetchNext "+JSON.stringify(obj)); v ...

Obtaining the body from a post request in Node.js: A step-by-step guide

When sending data with the id using the post method to my node server, I encountered an issue where req.body is returning as undefined in my node file. This is what my index.html looks like: <html ng-app="IMDBApp"> <body> <div ng-contr ...

Is there a problem with renaming files using the multer module's filename options?

I can't figure out why this isn't functioning as intended. The file upload feature is operational, but the generated name consists of a long string like 04504a8b6c715f933110c8c970a8f6ad. What I need is for the filename to include the original nam ...

Tips for aligning two objects side by side in HTML

Apologies for the basic question, forgive my ignorance but I am struggling with keeping two objects in the same line within the same division. Please take a look at the code below: <html> <head> <style> .search-input { width: ...

Is it possible to mimic a ref attribute with jest/rtl within a functional component?

I'm currently facing an issue with a functional component that includes a helper function. function Component() { imgRef = useRef(null) function helperFunction(node, ref) { if (!ref || !ref.current) return; ...do someth ...

Is it feasible to choose the component generated by this element?

My current dilemma involves a component that renders a form, however, it also has its own form "catcher". var FormUpload = React.createClass({ submit : function(){ var formdata =new FormData(); ...

Using Dropzone.js to bypass the Browse dialog when uploading files in integration tests with php-webdriver

Currently, I am implementing dropzone.js in my project. I have a specific requirement where I need to manually add a file to the queue without triggering the file browser dialog box. The dropzone has been initialized on the element with the class .imageDro ...

Tips for presenting JSON data retrieved using jQueryWould you like to know how

Is there a way to extract and display the user id from JSON values? I'm trying to access the user id value. $('User_id').observe('blur', function(e) { var txt = $('User_id').value; jQuery.ajax({ type: 'g ...

Tips for refining a list to only include items that contain every element from a specified array

Is there a way to search for all elements in an array and display them if they are all present? For instance, consider the following: const data = [ { "languages": ["JavaScript"], "tools": ["React", "Sass"] }, { "languages": ["Python" ...

a tutorial on linking component data to a prop value

Is there a way to connect the searchString value in my Vue component to the item value in the html template it uses? I need to pass this value to the method called in my Ajax request. Vue: Vue.component('user-container-component', { props: ...

Attempting to single out various entities within a JSON array through the use of radio buttons

I am currently developing a website to showcase sports teams' schedules. Each team has its own JSON file containing relevant information that I aim to display upon selecting the team from a radio button. For instance, let's consider the example ...

An AJAX script for dynamically adding, modifying, and removing records from a database

How can I implement a functionality where by pressing "-" the vote is removed from the database, and when any other number is selected, the vote will be updated in the database with that value? The default value of the dropdown list is votacion.votCalific ...

Performing XML API Requests with Node.js

Using the latest versions of node.js and express, I am attempting to make an API call to a site that returns XML data. Despite searching extensively online, I am unsure of the most current and efficient method for sending a request and receiving a response ...

Deleting multiple subdocuments and their related subdocuments with Mongoose

In my application, I have a Project document that contains an array of subdocuments structured as Tasks. Each Task has its own array of subdocuments with a schema called Comments. const projectSchema = new Schema({ _id: Schema.Types.ObjectId, name: { ...

When incorporating @babel/standalone, a JavaScript memory limit is exceeded

I am currently working on a React app that I developed using create-react-app. My main goal is to take user input as code and then evaluate it in order to render the output. Here's what I have attempted so far: import React, { Component } from &apos ...