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

What is the process of compiling TypeScript code?

When attempting to use tsc, I encountered issues. Even when having typescript but lacking tsc, the problem persisted. What steps should I take next? https://i.sstatic.net/Djgqb.png ...

Are there numerous instances of jQuery references both preceding and following the use of '$.noConflict'?

Managing a large project with thousands of PHP files can be challenging, especially when dealing with conflicting jQuery references that hinder the implementation of a desired plugin. Consider this scenario: <html> <head> ...

Create proper spacing for string formatting within an AngularJS modal

I am working with a popup that displays output as one string with spaces and newline characters. Each line is concatenated to the previous line, allowing for individual adjustments. Test1 : Success : 200 Test2 : Su ...

Please input a number that falls within a specified range

I need help with two text inputs that are connected v-model to a ref object. I also have two other refs, minimum (100) and maximum(1000). My goal is to allow users to input values within the range of the minimum and maximum values provided. If the value en ...

Tips for resolving the issue of loading not appearing on screen in Angular

How can I resolve the problem of the loading animation not appearing? Below is the code snippet: HTML <div *ngIf="tempThermometer | async as temp; else loading"> <ng-container *ngIf="temp.length !== 0; else noItems"> &l ...

Transforming JSON dates to Javascript dates using AngularJS and ASP.NET

How can I convert a JSON date /Date(1454351400000)/ into a proper date format using AngularJS and ASP.NET? $http.get('/home/GetProducts') .success(function (result) { $scope.products = result; }) .error(function (data) { ...

Crop and upload images asynchronously using Node.js

I need to resize an image into multiple sizes and then upload them to AWS S3. The specific resizing dimensions are stored in an array. To accomplish this, I am utilizing the async waterfall method along with the series method. async.each(crop_sizes, func ...

Having trouble with submitting the code - need help resolving the issue

I'm facing an issue with my submit cancel code. The JavaScript code I implemented for preventing the submission function on my page isn't working as expected. While it does work to a certain extent, it's not fully functional. I am seeking a ...

Utilizing AngularJS to dynamically inject HTML content into $scope

In my possession are the following files: index.html //includes instructions for passing arguments to the btnClick function in app.js <div ng-bind-html="currentDisplay"></div> app.js app.factory('oneFac', function ($http){ var htm ...

Verifying in PHP if the request is intended for a JavaScript worker

After doing my research on MDN for the referrer-policy, as well as searching through Google, DuckDuckGo and Stack Overflow, I still find myself stuck on a seemingly simple yet elusive issue. Journey of Data the browser sends a request to the server the ...

Applying a CSS style to a division element

Can I modify the style attribute of a div element using JavaScript? <div style="color:#0000FF"> <h3>This is a heading</h3> <p>This is a paragraph.</p> </div> I am interested in achieving the following: Changing th ...

Using the fetch/await functions, objects are able to be created inside a loop

In my NEXTJS project, I am attempting to create an object that traverses all domains and their pages to build a structure containing the site name and page URL. This is required for dynamic paging within the getStaticPaths function. Despite what I believe ...

Axios and Postman generate unique X-CSRF tokens

Why does the X-CSRF token I receive from my axios request differ from the one I get in Postman? Here is how I am retrieving it: headers: { "X-CSRF-Token": "FETCH" } Furthermore, I am unable to use the X-CSRF token from my axios request in Postman as it ...

Building a Modal in React and Triggering it for Display, followed by Making an AJAX Request upon Submission

Check out my CodePen snippet (minus delete ajax request): http://codepen.io/martincarlin87/pen/KzPWOw I've been diving into the world of React recently, and I'm working on converting a page in my web application to utilize React instead of just ...

"422 (Unprocessable Entity) Error When Submitting a Form in Rails Application

I recently delved into the world of ruby on rails a few days back. My current challenge involves transferring data from html tags to a ruby function using ajax. Below is the error message that has been giving me trouble: POST http://localhost:3000/ajax/o ...

Removing all comments from a post that has been deleted in MongoDB

I am currently following the MEAN stack tutorial provided by Thinkster () and I have encountered an issue with implementing delete operations. Here are the schemas I am working with: var PostSchema = new mongoose.Schema({ title: {type: String, required ...

A fresh PHP page escapes from the confines of an iframe and expands to occupy the entire

When calling a new url from inside an iframe, the goal is for the new url to break free from the confines of the iframe and appear full screen. The challenge lies in not having control over the call to the new php file, as it is initiated by a credit card ...

Looking for a way to utilize JavaScript to extract data from a database? I'm currently utilizing jQuery autocomplete and seeking to exclusively search for values within the database

Currently utilizing jQuery autocomplete <script> $(function() { var availableTags = [ "ActionScript", "AppleScript", "Scheme" ]; $( "#tags" ).autocomplete({ source: availableTags });}); </script> Any s ...

What is the best way to trigger a method after an old component has been removed from the DOM while navigating within Angular

I am facing a challenge where I need to execute a method on ComponentB after a routerLink is clicked, causing the navigation from ComponentA to ComponentB. It is crucial that this method is triggered only after the entire navigation process is complete (i. ...

Postman sends requests by utilizing AJAX and adhering to the same origin policy

I recently came across a Chrome extension called Postman that has proven to be incredibly useful. This tool is particularly handy for those working with RESTful applications. One thing that has puzzled me is how Postman is able to successfully send POST r ...