Querying a MongoDB collection for a specific entry based on its ID

Is it possible to update a user story in a project using MongoDB?

I am looking to update the fields of a specific user story within a project by selecting the project based on its id and then selecting the user story within that project based on its id.

Question: What MongoDB query should I use for this task?

MongoDB Database Cut

{
  "_id": ObjectId("4ecee95d6ce4004424000001"), //Project ID
  "owner": "test2",
  "stories": [
    {
      "_id": "75vUURHfE1bN9vkbwC2kR85s", //User story Id
      "title": "ok",
      "deadline": "10\/10\/2011",
      "description": "ok",
      "sp": "5",
      "value": "5",
      "roi": "1.00",
      "type": "story",
      "lane": 0
    },
    {
      "_id": "nTsa8x6vFJvdXfFtEHbcFIyl",
      "title": "test",
      "deadline": "10\/10\/2011",
      "description": "test",
      "sp": "5",
      "value": "5",
      "roi": "1.00",
      "type": "story",
      "lane": 0
    },
    {
      "_id": "i8Nd3HOhz7hZFzzInfCcapCe",
      "title": "test #2",
      "deadline": "10\/10\/2011",
      "description": "test #2",
      "sp": "5",
      "value": "5",
      "roi": "1.00",
      "type": "story",
      "lane": 0
    }
  ],
  "team": [

  ],
  "title": "ok"
}

Using socket.io, I retrieve the following data on a socket event:

JSON

var story = {
  _id: data.id,
  title: data.title,
  deadline: data.deadline,
  description: data.description,
  sp: data.sp,
  value: data.value,
  roi: data.roi,
  type: data.type
}

I aim to update the story within 'stories' in the mongo database with the provided JSON object above.

Answer №1

To accomplish this task, you have the option to utilize the $ operator (positional operator) in MongoDB:

db.coll.update( {"stories._id":"i8Nd3HOhz7hZFzzInfCcapCe"}, 
                {$set:{"stories.$.roi":"1.25"}}, false, true )

However, it is important to note that using _id may lead to issues as it could be a reserved name. I encountered problems when using this in the MongoDB 2.0.1rc-1 shell, so consider using something like this instead:

db.coll.update( {"stories.id":"i8Nd3HOhz7hZFzzInfCcapCe"}, 
                {$set:{"stories.$.roi":"1.25"}}, false, true )

There are some things to keep in mind: the $ operator will only work on the first matched item and cannot be used with upserts.

Furthermore, based on the information provided, it might be advisable to avoid embedding user stories and opt for a separate collection instead.

This approach can help prevent concurrency issues, especially if multiple users are editing the same project simultaneously, where managing arrays or implementing a locking mechanism becomes cumbersome.

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

Is it advisable to run npm as a superuser?

Having issues with npm errors while attempting to install/update packages without superuser permissions on a Linux system. An alternative solution would be to run sudo npm install <package>, but I am hesitant about whether this is the best approach. ...

classes_1.Individual is not a callable

I am facing some difficulties with imports and exports in my self-made TypeScript project. Within the "classes" folder, I have individual files for each class that export them. To simplify usage in code, I created an "index.ts" file that imports all class ...

Set up Express.js using npm

Just set up nodejs on my Ubuntu 14.04 system. Upon running node --version, I see that it's v4.4.2. Also, npm is installed with version 3.9.2. When I execute the command npm install -g express, this is the output I get: install express js Once the ins ...

Retrieving information from a .json file using TypeScript

I am facing an issue with my Angular application. I have successfully loaded a .json file into the application, but getting stuck on accessing the data within the file. I previously asked about this problem but realized that I need help in specifically und ...

Error in NodeJs: ReferenceError - the variable I created is not defined

Encountering an issue while attempting to use a module in my router file. I have successfully required it, but now I am seeing the following error message: ReferenceError: USERS is not defined at c:\work\nodejs\router\main.js:32 ...

Extend the express request object with Typescript and then export the modified object

Seeking to enhance the Request object from express with custom fields using typescript. Based on this particular source, I created a file named @types/express/index.d.ts containing the following code : import { MyClass } from "../../src/MyClass" ...

The request's body in the PUT method is void

I seem to be having an issue with my PUT request. While all my other requests are functioning properly, the req.body appears to remain empty, causing this error message to occur: errmsg: "'$set' is empty. You must specify a field like so: ...

What is the process for implementing a new requirement for 'confirmed' users when they log in with passport.js?

Looking to enhance the functionality of passport.js by implementing a conditional check to verify if the user account is confirmed. The plan is to insert an 'if statement' towards the end of the code, right after validating the user's email ...

Customizing X-axis labels for server-side chart rendering with PhantomJS and JSON data

Currently, I am utilizing phantomjs to generate png images of a highchart using a json file in a commandline script. Since the data is provided in JSON format, I am unable to apply xAxis.labels.formatter as I would in a web client version. However, since t ...

In Python 3, when using the requests library, a response of

When I run curl command, I receive back a unique hash value: $ curl "http://127.0.0.1:8002/hash/" -X POST -d 'data={"key":"value"}' { "hash": "9724c1e20e6e3e4d7f57ed25f9d4efb006e508590d528c90da597f6a775c13e5" } However, when using Python requ ...

Issues with Braintree webhooks and CSRF protection causing malfunction

I have successfully set up recurring payments with Braintree and everything is functioning properly. Below is an example of my code: app.post("/create_customer", function (req, res) { var customerRequest = { firstName: req.body.first_name, lastN ...

Tips for retaining form data after validation failure in a node.js application

Currently, I am working on validating form data using express validator. To keep the form fields populated even after a validation failure, I have split my routes and controllers into separate files. The validation process is being handled by express valid ...

Tips for structuring commands in Discord.js

I'm in the process of restructuring my bot's commands. I currently have a folder called commands with all my commands inside, but I want to make it more organized by categorizing them into moderators, fun, and global like this: commands > mo ...

Debugging in Node.js - automatic error message generation

Hello, I am a beginner in the world of nodejs (async) debugging and could really use some assistance when it comes to dealing with error messages. var l, m, opiton= {}; // It appears that the variable 'option' has been mistakenly spelled as &apo ...

Importing data from a CSV file into a Google Spreadsheet using the Python programming language

I am currently working on a Python script to transfer data from a CSV file to a Google Spreadsheet. While I have a good grasp of the fundamentals required for this project, I am struggling with formatting and parsing the data from the CSV file into the Goo ...

When using NextJS dynamic routes, they load successfully for the first time but encounter issues upon refreshing the

My NextJS app has a dynamic route called posts/[id].js. When the page initially loads, everything works perfectly. However, upon refreshing the page, the dynamically fetched data becomes undefined, resulting in the following error: Server Error TypeErr ...

When Typescript and React Native Imports Clash in an Express App, Resolving the Conflict of "npm run build" Command

When running my Express app using 'npm run serve', defined as 'npm run build && node lib/index.js' in the package.json scripts serve section, I encounter multiple duplicate declaration errors after installing React Native for a ...

Error encountered: No geographic indices found for executing a geoNear operation with Mongoose

Initially, I had divided the schemas but later nested them inside my overall document. Despite adding indexes and removing coordinates from location, there seems to be an issue with the nested points. Upon running get Indexes, it shows that there is an i ...

Developing a functionality to search for specific values within JSON properties

Hello, I have a question about implementing a partial search on a specific property within JSON data. Basically, what I'm trying to achieve is that if I type in "Jac" into the input field, it will search the JSON data for similar strings like Jacob, J ...

React | What could be preventing the defaultValue of the input from updating?

I am working with a stateful component that makes a CEP promise to fetch data from post offices. This data is retrieved when the Zip input contains 9 characters - 8 numbers and a '-' - and returns an object with the desired information. Below is ...