Removing an embedded document from an array in MongoDB using Mongoose when the document's status is set to false

I am in desperate need of a solution for this mongoose-related issue. My tech stack includes Express, Mongoose, and GraphQL.

To give you some context, I have two collections: users and groups.

user {
  name: string,
  groupAsMember: [groups],
  status: boolean
}

group {
  name: string,
  members: [user],
  status: boolean
}

The problem I'm facing is removing a user document from the group's user array when the user's status is set to false.

Here's what I've tried so far:

return User.findOneAndUpdate(
  {_id: id},
  {$set: {status: false}},
  {new: true, useFindAndModify: false}
)
  .exec()
  .then(async (user) => {
    return await Group.updateMany(
      {'_id': {$in: user.groupAsMember}},
      {$pull: {"members.id": user._id}},
      {new: true, useFindAndModify: false}
    )
      .then((user) => {
        console.log(user);
        return user;
      })
      .catch((err) => {
        console.log(err);
        return err;
      })
  })
  .catch((err) => console.error(err));

I have experimented with different online solutions as shown in the commented-out code snippets. However, I continue to encounter errors like:

Cannot use the part (id) of (members.id) to traverse the element ({members: [ ObjectId('5f985ffc59355439ac59598e'), ObjectId('5f9a328c83eb44243021d756') ]})

unknown top level operator: $eq

The positional operator did not find the match needed from the query.

If you have the answer to this puzzling issue, your help would be greatly appreciated. Thank you in advance.

Answer №1

If you haven't already, give this a try. It should do the trick for you:

 { $pull: { members: { _id: { $eq: user._id } } } }

Additionally, if you're utilizing async await, there's no need to use .then since await will always return a promise. Your code should look like this:

    return await Group.updateMany(
      {'_id': {$in: user.groupAsMember}},
      { $pull: { members: { _id: { $eq: user._id } } },
      {new: true }
    )

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

Changing the event handler of a jQueryUI accordion dynamically from "click" to "mouseover" as needed

I am facing a scenario where I need to drag an item from a list and drop it into a target within an accordion. The challenge is that the target may be in a panel that is not currently open. To address this issue, I am looking to dynamically switch the acc ...

Center Align Images in HTML List Items

Hey there! I'm currently diving into the world of web development with responsive design, but I'm still a bit of a newbie. So please bear with me as I try to explain my issue in detail. If you need more information, just let me know! My current ...

Unable to view cross domain cookies within the browser's development tools

I am currently working on a web application that has an Angular front end running on http://localhost:4200 and a NodeJs backend running on http://localhost:3000. When a user successfully logs in, a cookie is set from the backend containing a token. However ...

Struggling to find multiline content in a SWIFT message using regex

Looking into a SWIFT message using RegEx, here is an excerpt: :16R:FIN :35B:ISIN CH0117044708 ANTEILE -DT USD- SWISSCANTO (CH) INDEX EQUITY FUND USA :16R:FIA The goal is to extract information in group 3: ISIN CH0117044708 ANTEILE -DT USD- SWISSCANTO (C ...

How can I extract the return value of a JSON object and store it in a variable?

I am attempting to develop a dynamic chart by utilizing data retrieved from a function housed inside a JSON object. The JSON object is fetched through the Relayr Javascript API, and looks like this: relayr.devices().getDeviceData({ token: tok ...

Creating an asynchronous function in a Vue.js component that utilizes the Lodash library

I'm struggling with writing an async function correctly. Can someone provide guidance on how to achieve this? async search (loading, search, vm) { let vm = this _.debounce(() => { let ApiURL = '/users/' } let { res } = await ...

The http url on an iPad in the src attribute of an HTML 5 video tag is malfunctioning

Having trouble loading a video on iPad using an http URL in the src attribute of an HTML5 video tag. Both static and dynamic approaches have been attempted, but it works fine on web browsers. Here is an example of the code: Static: <!DOCTYPE html ...

Utilize context.isPointInPath(x, y) in HTML5 Canvas for intricate shapes that contain multiple paths

I am currently working on a project that involves drawing a complex shape composed of 6 thin lines and two thick lines. In my code, I have defined 8 paths to achieve this: context.save(); context.lineWidth=2; var TAB_ABSTAND=10; var T ...

Guide on accessing an API from a separate file in a Node.js Express application

As a newcomer to using Express and Node, I am encountering the task of consuming a third-party API. I have knowledge on how to call functions from one file to another using module.exports. However, I am unsure about how to call an API that is written in th ...

Guide to accessing a mongoose model that is not part of your current project

I am currently developing a microservice for a Referral System in conjunction with an existing app that already has its main backend up and running. This Microservice will serve as an extension to the current setup. I have created a Referral Model structur ...

Avoid triggering the parent modal to close when a child element is clicked in VueJS

In my Vue application, there is a situation where I have a button called "detach button" with a @click function inside an element that is clickable. When clicking on this parent element, it triggers another @click function and toggles a Bootstrap modal eve ...

Display all information associated with the class that matches the clicked ID

Can anyone help me with a Jquery question? I am trying to display all data with the same class when I click on it. I have created a list of clickable items. When I click on an item, the corresponding data should be shown. However, the code I wrote is not ...

Utilizing Boolean Operators in JavaScript with Thymeleaf: A Guide

When incorporating Boolean conditions in JavaScript with Thymeleaf using th:inline="javascript", an exception is thrown which appears as follows: org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 22; The entity name must immediately follow the ...

Protractor - Easily locating elements by targeting their children

I am attempting to modify the text of the input element, but I am having trouble identifying it. The element does not have an id or any other distinguishing characteristic. Additionally, this same object is repeated multiple times in the code, making it di ...

Unable to modify the hover color on the image or icon

After creating a circle icon with an image in the center, I wanted to make the image change colors on hover. The main focus of the icon is the circle itself. In my attempt to achieve this effect, I included the following code for the circle icon: .circle- ...

Uploading multiple files to MongoDB's GridFS system

app.post("/", upload.single("avatar"), function(req, res, next){ var writestream1 = gfs.createWriteStream({ filename: req.file.filename }); var writestream2 = gfs.createWriteStream({ filename: req.file.filename }); fs ...

Is there a way for me to update a Link To containing a parameter by using history.push with a parameter inside a table cell?

Hey there! I'm working on some code and wondering if it's doable to replace the Link To with a history.push, including the following parameter, like so: <TableCell style={{width: '10%'}}> <Link to={`/run-id/${item.run_ ...

What is the best way to showcase a specific column from a dataset using Vue.js and axios?

Hey there, I'm still getting the hang of all this and haven't quite mastered the jargon yet. Here's what I need help with: I managed to retrieve data from my SQL database using axios, and when I check in (f12) - network - preview, it shows: ...

Experiencing a RepositoryNotFoundError in TypeORM, although I am confident that the repositories are properly registered

I am creating a new application using Next.js + TypeORM and encountering an issue with the integration. RepositoryNotFoundError: No repository for "User" was found. It seems like this entity is not registered in the current "default" connection? Althoug ...

Creating a bespoke validation in AngularJS to verify if the selected date falls within a specific range of weekdays

Hey there! I'm looking to enhance the validation process for a date input field in a unique manner. Currently, my default validation setup looks like this: <div> <input type="text" name="firstName" ng-model="appointmentForm.firstName" ng- ...