Understanding Mongodb: the process of populating a schema that is referenced within another schema using an API

Looking to make adjustments to my Api in order to populate a referenced schema. Here's the schema I am working with:

export const taskSchema = new Schema ({
    user:{
        type: String,
        required: true
    },
    project: { 
        type: String,
        required: true
    },
    issue: {
        type: String,
        required: true
    },
    title: {
        type: String,
        required: true
    },
    records : [{
   
        _domain: {
            type: Schema.Types.ObjectId,
            ref: 'TaskDomains'
        },
        time: {
            type:Number
        }
    
    }],
    
   
    dateCreated: {
     
        type: Date,
        default: Date.now
    }
});

Now, let me show you the taskDomain schema :

export const TaskDomains = new Schema ({
    label:{
        type: String,
        required: true
    }

});

I'm struggling with editing the following post method to populate the referenced TaskDomain schema. Take a look at the method below:

import * as mongoose from 'mongoose';
import {taskSchema,TaskDomains} from '../models/tasks.model';
import {Request, Response} from 'express';

const Task = mongoose.model('Task', taskSchema);
const domain = mongoose.model('domain', TaskDomains);
export class taskController{
public addNewTask (req: Request, res:Response){
        let newTask = new Task();
        newTask.user = req.body.user;
        newTask.project = req.body.project;
        newTask.issue = req.body.issue;
        newTask.title = req.body.title;
        newTask.dateCreated = req.body.dateCreated;
        newTask.records = new domain(req.body._domain);
        newTask.records = new domain(req.body._domain.label);
        newTask.records = req.body.time;

        newTask.save((err, task)=>{
            if(err){
                res.send(err);
            }
            res.json(task);
        });
    }
    }
I could use some guidance on modifying the post method. So far, my attempts have not been successful.

Answer №1

Your current method isn't quite right - you should start by saving the domain document first and then create the task document once the save is successful.

Here's a suggestion:

public addNewTask (req: Request, res:Response){

    // First create and save the domain document before creating the task document, and make sure to store its _id in the task document
    let _domain = new domain(req.body._domain);
    _domain.save((err,_domain)=>{
        let newTask = new Task();
        newTask.user = req.body.user;
        newTask.project = req.body.project;
        newTask.issue = req.body.issue;
        newTask.title = req.body.title;
        newTask.dateCreated = req.body.dateCreated;

        // Store only the _id of the newly created _domain document here
        newTask.records = [{
            _domain : _domain._id,
            time : req.body.time
        }]

        newTask.save((err, task)=>{
            if(err){
                res.send(err);
            }
            // If you want the _domain object populated in your records array, you can use .populate()
            Task.populate(task,{path : records._domain},(err,task) =>                                 
            {
               res.json(task);
            })
        });
    })
}

Assuming your request body has this structure :

{
    user : "user_name",
    project : "project_name",
    issue : "issue_name",
    title : "title_",
    dateCreated : "date",
    _domain : {
        label : "some_label"
    },
    time : 12345
}

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 considered a best practice to utilize JavaScript for positioning elements on a

I recently started learning JavaScript and jQuery, and I've been using them to position elements on my website based on screen and window size. It's been really helpful, but I'm starting to wonder if it's a good practice since it makes ...

What do you call a JavaScript function when it has a name

This code is confusing to me. It's not the usual JavaScript syntax for a function that I know of. Is this a specific function? Or perhaps it's a callback for when an update event occurs? Apologies for these beginner questions, as I am quite new t ...

Remix is throwing a Hydration Error while trying to process data mapping

While working on my Remix project locally, I encountered a React hydration error. One thing I noticed is that the HTML rendered by the server does not match the HTML generated by the client. This issue seems to be related to the Material UI library usage. ...

I am looking to update the background color of the material UI helper text

In the image below, you can see that my background color is gray and my text field color is white. When an error is shown, the text field's white color extends and the password error message doesn't look good. I want the text field to remain whit ...

Issues with Node JS app's handling of php mailer code

I've made a basic website using the Node JS framework and included a php mailer for handling the contact form. Unfortunately, I'm facing issues getting it to function properly. Could it be possible that there is an underlying problem with Node JS ...

Ensure AngularJS ng-show and ng-hide are more secure

When using AngularJS, my goal is to conceal an element so that only authenticated users can access it. Although the ng-hide directive works, there is a vulnerability where someone could modify the class assigned to the element (ng-hide) using Developer To ...

Why does one image render while the other with the same src does not?

Has anyone encountered a situation where there are 2 img tags with the same src, "images/export.png", but one displays correctly while the other doesn't? Any insights on how this discrepancy can occur? Here's some background information: -The w ...

What is the method for assigning a class name to a child element within a parent element?

<custom-img class="decrease-item" img-src="images/minus-green.svg" @click="event => callDecreaseItem(event, itemId)" /> Here we have the code snippet where an image component is being referenced. <template&g ...

Leverage the power of AJAX and PHP to securely save comments for future

I have coded a JavaScript function that uses POST and GET methods to send comments from an input field and retrieve them when the page reloads. However, I am unsure of how to handle the data after it is sent in order to save it and access it again later. E ...

Ways to incorporate a php file based on the user's selection

I have numerous div elements, possibly a dozen or two, such as... <div class="mydivs" id="firstdiv"></div> <div class="mydivs" id="seconddiv"></div> <div class="mydivs" id="thirddiv"></div> <div class="mydivs" id="fo ...

The isolate scope variable is becoming undefined within the link function

When working with a directive that takes a data object and a function in its isolate scope, I encountered an issue. Inside the link function, I declared a method to be triggered on a button click event. The problem is that while the value passed to the me ...

Production website fails to display updated data while the localhost version operates without issues

Having trouble fetching data from my database in a production setting. The code functions fine on localhost, but fails to grab updated data when live. Below is the relevant snippet: import {connect} from "@/dbConnection/dbConnection"; import Post ...

Having difficulty modifying the values of my input types on the edit page

After successfully adding user values from the add user page, I encounter an issue when attempting to edit these values such as firstname and lastname on the edit page. Please review the code snippet below for any possible errors. import React from ' ...

When calling mongoose.connect(), the initial parameter must be a String but it was found to be

I am facing issues while setting up the test database for testing purposes. The connection error shown when trying to connect to MongoDB using Mongoose is: throw new MongooseError('The `uri` parameter to `openUri()` must be a ' + ^ MongooseEr ...

Is it possible to globally define a namespace in Typescript?

Seeking a way to make my Input module accessible globally without the need for explicit path definitions. Currently, I have to import it like this: import { Input } from "./Input/Input";. Is there a method to simplify the import statement for modules con ...

How can I ensure that I am only retrieving the first object within a "for loop" in vuejs and returning its value without getting the rest?

Why am I only able to retrieve the value of the first object in my "for loop" and not all three values as intended? var app = new Vue({ el: '#app', data: { myObj: [ {name: 'Hello', age: 10}, {name: ...

Is there a way to retrieve the textFrame where the cursor is currently located?

While inputting text into a frame, I am looking to execute a script. I want this script to target the specific text frame where my cursor is located. How can I reference this particular textFrame using Javascript? ...

JavaScript's onclick function for clearing dropdown fields will only work once for each specific dropdown field

I have scoured all the related questions and answers on StackOverflow, but none seem to address my specific issue. Here is the HTML code I am using: <select name="search_month" onclick="javascript: $('#categories').val(null);" id="months"> ...

Both the maxlenght and ng-maxlength directives appear to be ineffective in AngularJS

In my HTML file, I have the following input: <input name="password" id="newPasswordConfirmation" ng-model="newPasswordConfirmation" type="number" inputmode="numeric" placeholder="" required ...

Displaying a div in Vue.js when a button is clicked and an array is filled with

Hey there! I'm having an issue with displaying weather information for a specific location. I want to show the weather details in a div only when a button is clicked. Despite successfully fetching data from the API, I'm struggling to hide the wea ...