Updating a Mongo Record using the ID obtained from another Record's retrievalI hope this meets your needs

One of my current tasks involves creating an API endpoint with specific functionality. The goal is to input an Object ID into the path, locate the record associated with that ID, access a particular field within this object which contains another ObjectID for a different database entry, and ultimately retrieve that record in order to increment a specified field.

In essence, there exists a child->parent relationship between certain records, and I am seeking a method to increase a certain field within the parent record by providing the child's id through the API endpoint.

The presented code snippet demonstrates how the basic child increment was achieved. Now, the focus shifts towards implementing a similar mechanism for the parent record. How should I approach this task?

router.get('/today/parent/up/:id', function(req, res){
        var collection = db.get('Activity');
        collection.update({
            _id: req.params.id
        },
        {
            $inc: {
             "repetitions.today": 1,
             "repetitions.total": 1 
            }
        }, function(err, activity){
            if (err) throw err;
            res.json(activity);
        });
})

Answer №1

To begin, utilize MongoDB references. Detailed documentation can be found at: https://docs.mongodb.com/manual/reference/database-references/

Additionally, refer to the mongoose documentation available here: http://mongoosejs.com/docs/2.7.x/docs/populate.html

The process involves creating schemas with references as shown below:

var mongoose = require('mongoose')
, Schema = mongoose.Schema

var PersonSchema = new Schema({
    name    : String
, age     : Number
, stories : [{ type: Schema.ObjectId, ref: 'Story' }]
});

var StorySchema = new Schema({
    _creator : { type: Schema.ObjectId, ref: 'Person' }
, title    : String
, fans     : [{ type: Schema.ObjectId, ref: 'Person' }]
});

var Story  = mongoose.model('Story', StorySchema);
var Person = mongoose.model('Person', PersonSchema);

You can then use the .populate() method to retrieve data from referenced models, make modifications, and save them using .save(). Remember to carry out these operations on the populated model itself, not the parent one. For instance, if you have an author referencing books, you can execute the following request:

author.findOne({'name': 'King'}).populate('books').exec((err, king) => {
  let book0 = king.books[0];
  book0.title = 'I need to change this one';
  book0.save((err, data) => {
    console.log('saved referenced object')
  }
})

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

Updating an object with a new key-value pair is not successful

Having Trouble Assigning a New Key and Value to an Object I am facing an issue where I am trying to add a new key named CreatedUser with an object/array value to a post, but it doesn't seem to be working as expected. Can someone please assist me with ...

Utilizing NextJS App in a Docker Container with Production Environment Variables

Everything runs smoothly when testing and using my NextJS Application with .env.local. However, the issue arises during a production build for deployment as it fails to locate the .env.production values, even though they are an exact replica of .env.local ...

Using the digitallyseamless/nodejs-bower-grunt docker image to containerize npm and bower installations

I've been exploring the possibilities of using Docker to execute npm and bower install commands. Below is my setup: ./package.json { "name": "bignibou-client", "version": "0.1.0", "engines": { "node": "0.10.x" }, "devDependencies": { ...

Guidelines for effectively sending a redirect to a URL in an Express application

For the past few days, I've been struggling to send a proper redirect request in my App. Here's what should happen: If I attempt to perform an action that requires me to be logged in, my express app should automatically redirect to the login URL. ...

What is the mechanism by which a callback function operates in conjunction with Azure Blob's createReadStream method for streaming

I have a function that successfully retrieves a stream object containing a blob from Azure Storage: module.exports.readFileToStream = function(fileSpec, callback){ return blobService.createReadStream(fileSpec.container, fileSpec.file, function(err, res ...

Creating a Mongoose model with an array property that includes instances of the same model as the parent

My current challenge involves creating a Note object with a subnote property that should be of the same type as the parent model. Currently, I have achieved this by creating two identical models with different names and having them reference each other. He ...

Where can Vue.js be found?

After dedicating an hour to watching instructional YouTube videos on Vue.js, I am still struggling to grasp the language! In the past, I have worked with Node.js, Jquery, and Mongodb to develop websites... I believe that web applications require multiple ...

How can I instruct mongoose to exclude null parameters when present?

User Query Location.find( { "$text":{ "$search":"req.body.searchKey" }, "location_type":"req.body.location_type", "address.state_ut":"req.body.state_ut&quo ...

The destination path specified in npm copyfiles is not accurate

Currently, I am utilizing the npm package known as "copyfiles" within my buildscript. However, I have noticed that the target directory does not match the expected output. "copy-template": "copyfiles \"./src/**/*.html\" \"dist\"", The ...

Pictures fail to appear in https but are visible when using http

After successfully building my first personal website using the MERN stack, I encountered an issue when trying to deploy it on AWS Lightsail. While everything seemed to be working fine in HTTPS mode, the images were not displaying properly. When clicking o ...

Can we program a system that automatically deletes messages that do not include the text "ew"?

Currently developing a basic server with a unique feature - responding with "ew" in the chat. Is there a way to automatically delete any message that does not include the word "ew"? Appreciate your help! ...

Issues encountered when attempting to install an npm package in Node.js version 18.18.2

Just recently, I decided to download Node.js from this website using the macOS installer. The installation process seemed to go smoothly until I encountered an issue while trying to download a npm module from here. I executed this command in the terminal: ...

Sending Data to Backend Using React Router and Express with an Ajax POST Request

I've encountered an issue while attempting to submit a basic form within a React component: class UploadPartList extends Component { constructor(props) { super(props); this.state = { data: [] }; this.handleSubmit = this.handleSubmit.bi ...

What causes the error message "TypeError: client.db is not a function" to appear in Node.js and what steps should be taken to resolve it?

Struggling with writing a MongoDB aggregation query in Node.js. Despite my best efforts, the codes I implemented are not working as expected and throwing the error: TypeError: client.db is not a function const { MongoClient, ObjectId } = require(' ...

The JSON data sent from the primary Electron process is arriving as undefined in the renderer

Currently delving into an Electron project to explore the technology. It's been a captivating and enjoyable experience so far as I work on creating a basic home controller for my IoT devices. However, I've encountered a minor issue. In my main.js ...

The asynchronous method in a Mongoose schema does not pause for completion

Here is the code snippet that I am currently working on: const user = await User.findOne({ email }).select('+password'); console.log(' user value : ', user); const boolean = await user.comparePassword(password, user.password); console.l ...

The ENOENT error code 4058 occurred while attempting to create a new react application using

Every time I run the command npm create-react-app my-app, I encounter an error like this: npm ERR! code ENOENT npm ERR! syscall spawn C:\Windows\System32; npm ERR! path C:\Users\Administrator\Documents\th-wedding\templa ...

Despite encountering multiple failures with my Ajax POST request using Express and Plivo, I continue to receive duplicate SMS notifications on my phone

I am currently working with Express, React, Ajax, and Plivo. My issue involves an ajax POST request that I have set up to send data (user phone number and text message) from the client to my express server. While the text message is successfully delivered ...

Guide to querying MongoDB for data based on date using Express

I am attempting to retrieve data from a mongoDB collection based on the creation date. Date format for retrieving data: yyyy-mm-dd (e.g. 2015-04-14) Format stored in collection: timestamp: "2015-04-13T17:50:48.761Z" Controller : $scope.getExpenc ...

No response is generated by Express upon completion of bulk insertion

Looking to efficiently insert data in mongodb using mongoose. The data is being saved in the database without any issue, but there seems to be an issue with sending a response back from express. We have tried methods like insertMany and bulkWrite try { ...