Posting a reference ID to the parent collection in MongoDB is not allowed

Trying to add two records into mongoDB: one as a new collection and the other as a reference ID.

Here is a sample schema: Company{ name: Acme Company, Locations: [refID] }

The ID and location payload will be sent in the request body.

addNewLocation: (req, res) => {
        
        let {id, ...payload} = req.body;
        
        db.Location.create(payload)
            .then( record => {
                let refId = record._id
                db.Company.findOneAndUpdate( {_id: id} , { $push: { locations: refId } }, { new: true })
            })
            .then( result => {
                res.status(201).json({success: true},{result})
            })
            .catch( err => {
                res.status(422).json({success: false},{err})
            })
    }

When viewing the update on Robo3T, it seems that a document is being inserted into the location but not the ref ID in the companies collection. Any thoughts on what might be causing this?

Answer №1

Perhaps you are confusing the spelling of locations in your schema when trying to push a reference. It could be Locations as your schema field name, or you may need to change it to locations. You can test this by updating your company schema with the following code:

 {
    name: String,
    locations:[
      {
      type: Schema.Types.ObjectId,
      ref: "Location"
     }
    ]
 }

Answer №2

addNewLocation: (req, res) => {
    let { companyID , ...data } = req.body;

    db.Location.create(data)
    .then(({_id}) => {
       return db.Company.findOneAndUpdate(companyID, {$push:{locations: _id}},{new: true})
    })
    .then(()=>{
        res.status(201).json({message: 'Location added successfully'})
    })
    .catch((error)=>{
        res.status(422).json({message: 'Failed to add location'})
    })
}

This modified code adds a new location with proper error handling.

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

I must adjust the size of images based on the size of the viewer's screen

Hello everyone, I could really use some assistance as I am not an expert programmer but just a site admin. My issue is this: I have a website running on PHP and I want to display images to my members while keeping them within specific size limits so they ...

Troubleshooting Connection Issues with Node.js, Mongoose, and MongoDB

Struggling to establish a connection between Express JS and MongoDB using Mongoose, encountering persistent errors. How can this be resolved? const express = require('express'); const mongoose = require('mongoose'); const app = express( ...

Updating a slider based on the values of two other sliders can be achieved by implementing a

I am working on a project that involves three input sliders. I need the third slider to display the product of the values from the first two sliders. Additionally, I want the value of the third slider to update dynamically whenever the values of the first ...

Restarting the Application Server on Vercel: What to Do When Only the "Redeploy" Button is Present?

I have my Next.js application hosted on Vercel, and I recently encountered a situation where I needed to restart the server. However, in the Vercel dashboard, there is only a "Redeploy" option available and no clear "Restart" option. After receiving an al ...

Show divs in identical position when clicking

There are 4 section divs that need to be displayed in the center of the page when clicked, but the last one appears further down. This is likely due to the flex box nature. What is the best way to ensure all sections appear at the exact same location? Ano ...

Linking Multiple Applications Through an Express Server Proxy

I have been experimenting with creating a reverse proxy for multiple node applications. Here is an example of how it works: app.use('/', proxy('http://localhost:5010/')); app.listen(8000, (err) => { if (err) { return console.err ...

Ways to distinguish XmlHttpRequest Access-Control-Allow-Origin issues from regular network errors

When making an ajax request, there is a possibility of encountering an error, indicating a failure to establish communication with the intended target (no status code returned). To handle these errors, you can use the following code: var oXhr = new XMLHt ...

Resolving cached CSS and JS files through the use of local storage

My customers frequently express frustration over not seeing the improvements I've made to my CSS or JS effects. The issue seems to be related to cached files. Perhaps this code snippet could provide a solution: $(document).ready(function(){ va ...

Next.js encountered an API resolution issue while uploading a file, resulting in no response being

Even though my code is functioning properly, a warning appears in the console: The API call was resolved without sending any response for /api/image-upload This particular endpoint is responsible for uploading an image to Digital Ocean's object sto ...

A guide to testing window.pageYoffset in webdriverIO using chai assertions

When conducting a selenium test using WebDriverIO and Chai, I encountered the need to capture the position of window.pageYoffset. Unfortunately, I was unable to find a direct way to do this in WebDriverIO. My initial attempts involved: browser.scroll(0, 2 ...

Running Spring Boot and MongoDB on Heroku connected to an Atlas database

I encountered a Null Pointer Exception while trying to deploy my application on Heroku, as seen in the exception log below: 2021-01-28T23:18:59.561585+00:00 app[web.1]: Caused by: java.lang.NullPointerException: null 2021-01-28T23:18:59.561585+00:00 ap ...

What is the best approach to accumulate model data in an Angular JS service or controller through a series of consecutive calls?

I am facing a challenge where I need to display the results of multiple REST server calls on a single page using AngularJS. The initial call retrieves details about a specific product, including the IDs of other related products. My goal is to not only s ...

Performing an HTTP request response in JavaScript

I am trying to make an HTTP request that returns the data in JSON format using 'JSON.stringify(data)'. var xhr = new XMLHttpRequest(); xhr.open("GET", "/api/hello", true); xhr.send(); xhr.onreadystatechange = function () { console.log(xhr.r ...

From Google Assistant to Python Results

Is there a way to control a Bitcraze Crazyflie drone using Google Home? I'm looking to give the command "Drone fly to x3 y4" which will be processed through Firebase and result in the Google Assistant Output: "Flying to x3 y4". Additionally, I need an ...

Pass along an event from a child component to its parent in Vue 2

As a newcomer to JS and Vue, I appreciate your patience with my learning curve :) I've set up a table using two Vue components: a parent (representing the table - orders) and a child (representing the row - order). Each row in the table has a button ...

Accessing UPI apps such as Google Pay through deep linking from a web application

I am currently exploring the possibility of deep-linking to individual UPI apps, like Google Pay, that are installed on a user's phone. The goal is for users to be seamlessly redirected to their preferred UPI app when they click on the respective icon ...

Deleting an item in MongoDB and Mongoose using its unique identifier

I'm encountering an issue with robots.remove where it says robots is not defined. I have been trying to figure out the root cause of this problem but haven't been successful so far. Any assistance would be greatly appreciated. Thank you. mongoos ...

Incorporating a YouTube channel into mobile websites

While it's relatively easy to embed single YouTube videos in mobile pages with the help of Google, I'm still struggling with embedding a whole channel. The issue seems to revolve around the screen width, and my attempts at using JavaScript have n ...

Enhancing Javascript Dialog Box with a Touch of Animation

Collaborating with the incredibly talented Mark Eirich has been an amazing experience. We have been working on revamping a JavaScript dialog box together, and Mark has set up something on JSFiddle that will be incredibly beneficial. However, I am seeking a ...

AngularJS item

I am a beginner in AngularJS and need help with printing object attributes in AngularJS controller. @RequestMapping(value = "/rest/getById", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @RolesAllow ...