Working with Associated Models in MongoDB using Sails.js

I am utilizing the Waterline ORM within Sails.js to construct a sample application with a model named 'Category'. Since a category can contain multiple subcategories, I have implemented a one-to-many association for this model:

module.exports = {

  adapter: 'mongo',
//  adapter: 'someMysqlServer',

  attributes: {
    categoryTitle: {
      type: 'string',
      required: true
    },

    parentCat: {
      model: 'category'
    },

    subCategories: {
      collection: 'category',
      via: 'parentCat'
    },

    articles: {
      collection: 'article',
      via: 'category',
      required: false
    }

  }
};

In the CategoryController.js file, I have a create method which checks if the new category has a parent category assigned. However, I find the code messy and the parentCat field in MongoDB is always empty even after trying to assign a parent category in the form submission. Here is my implementation:

 create: function(req, res, next) {
        var params = req.allParams();

        // set parent category if exists
        if (params.parentCat) {

            Category.findOne({categoryTitle : params.parentCat})
                .exec(function(err, category) {
                if (err) {
                    return false; //not found
                } else {
                    params.parentCat = category.id;  //found the parent category
                    console.log('parent cat id is: ', category.id);
                }
            });
      }

        Category.create(params, function(err, newCategory) {
            if (err) {
                return next(err);
            } else {
                console.log('new category created');
            }
            console.log('successfully added the category: ' + newCategory.categoryTitle)
            res.redirect('/category');
        }); // create the category
    }

Answer №1

Your code problem lies in the callback function.

I have developed a new version of the code utilizing the async feature that is already integrated into your sails app. Hopefully, this will resolve the issue for you.

create: function(req, res, next) {
    var params = req.allParams();

    async.waterfall([
        function(callback) {
            // Check and set parent category if it exists
            if (params.parentCat) {
                Category.findOne({
                        categoryTitle: params.parentCat
                    })
                    .exec(function(err, category) {
                        if (err) {
                            return false; //category not found
                        }
                        params.parentCat = category.id; //found parent category
                        console.log('parent category id is: ', category.id);
                        callback(null, params);
                    });
            } else {
                callback(null, params);
            }
        },
        function(params, callback) {
            Category.create(params, function(err, newCategory) {
                if (err) {
                    return next(err);
                }
                console.log('Successfully added the category: ' + newCategory.categoryTitle);
                callback(null, newCategory);
            }); // create the category
        }
    ], function(err, result) {
        console.dir(result);
        res.redirect('/category');
    });
}

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

NodeJS process that combines both client and server functionality

Attempting to develop a test echo server with both client and server in the same node process. When the code is split into two files (server and client), it functions correctly, but when combined into one file, it fails. How can I make it work within a sin ...

What is the proper method for securing this?

Trying to retrieve 'this' within a method that is invoked by pressing a button, where this points to both the class and the pressed button: p.myVar = 'apple'; $('.go').on('click', this._init); p._init = function(e ...

Combining objects using ES6 import/export with async/await functionality

I am facing a situation where I have two files named config.js and config.json and my goal is to combine them into one object and then export it: config.json { "c": 3 } config.js import fs from "fs"; import fse from "fs-extra& ...

Unable to showcase JavaScript outcome on the HTML page

I have been working on creating a JavaScript function to calculate the Highest Common Factor (HCF). While testing my code in the VS Code console, the correct value is displayed. However, I'm encountering an issue when trying to display the result on t ...

Searching for hidden elements within a div using a filter option

An accordion is located inside a div and a search box has been added to the div with the intention of serving as a search filter. Some accordion elements are visible within the div while others are hidden. The problem arises when trying to make the filter ...

object stored in an array variable

I am looking to find out if there is a way to access a variable or function of an object that has been added to an array. I want to display all the objects in the array on a web page using a function that will return a string containing their content. Thi ...

Execute the function only in response to changes in the data

I have a scenario where I am making an ajax call every 3 seconds to keep my app updated with rapidly changing information. However, the expensive function that I run inside the $.done() callback is causing my app to slow down. I want to optimize this proce ...

Altering the data in the database array is not within my capability

I'm having trouble updating the comment status, specifically the "approve" field. I've set up an AJAX script and it seems like the backend is working because I get a message after clicking the button. However, for some reason, the "approve" value ...

Checking if the current time is within 45 minutes of a specified time and if the present time is later than the specified time using an

I'm currently learning how to work with 'angularJS' and struggling with creating a function that can determine if a given 'time' is within 45 minutes of now, and also if the 'time' has already passed (meaning, if now is a ...

When hovering over items in the navigation bar, the entire bar expands seamlessly

I've spent countless hours trying to troubleshoot an issue with my dropdown menu that expands whenever I hover over it. The bar stretches out to accommodate the list of dropdown contents and then reverts back to normal when I move my cursor away. My a ...

Error TS2403: All variable declarations following the initial declaration must be of the same type in a React project

While developing my application using Reactjs, I encountered an error upon running it. The error message states: Subsequent variable declarations must have the same type. Variable 'WebGL2RenderingContext' must be of type '{ new (): WebGL2 ...

Mastering the art of styling strings in the Terminal with Chalk - the ultimate guide

I've been trying to use the chalk terminal string styling package in iTerm2, but I'm not seeing any colored string results despite following all the installation steps. Even a simple console log like console.log("hello"); in my chalk.js file isn& ...

Eliminating Repetitions in Array of Objects by Filtering Out Objects with Matching Properties

I am currently working with an array of objects where I need to identify duplicates based on specific properties (first and last names). Below is my attempt at solving this issue: The expected output should resemble: [ {first:"John", last: "Smith", id: ...

What is the process for translating HTML elements into JSX format?

I have a couple of inquiries. 1.) I am working on a basic reactjs component. How can I transform it into JSX? I want the code to follow the reactjs style. 2.) If I receive an array from the backend in this format [ '/parent-folder-1/child-folder ...

Tips for adjusting column width with flexbox intersections

I am currently working on a React web application that has minimal styling. I have divided the content into 3 columns, with the leftWrap being col-3, rightWrap being col-4, and the remaining width is for centerWrap. I want to apply flex ...

Exploring the Power of JQuery and Iterating with For-

I'm currently facing a small issue with my code. I need to retrieve information about each module when I display the hidden table row. The information is fetched from the page {modules/$moduleid}. While I understand how to utilize AJAX, my challenge l ...

Passing parameters from a div to a single page component in Vue.js: A complete guide

There is code that appears on multiple pages: <div id="contact-us" class="section md-padding bg-grey"> <div id="contact"></div> <script src="/dist/build.js"></script> </div> Included in main.js is: im ...

Compiling Typescript with module imports

In my project, I am working with two files named a.ts and b.ts. The interesting part is that file b exports something for file a to use. While the TypeScript compiler handles this setup perfectly, it fails to generate valid output for a browser environment ...

What are the steps for enlarging the display containing components with the 'position: absolute' style?

How can I magnify the screen with the following code? .drawing-board { width: 25%; height: 25%; background-color: black; position: relative; /* transform: scale(2, 2); */ } .drawing-board .box-1 { width: 20px; height: 20px; background-c ...

Filtering through values stored in the .data() object

UPDATE: Don't forget to check out the jsfiddle for this question! I am working with an SVG image that contains various paths and shapes, each enclosed in a <g> element with its own unique id. For the sake of simplicity, I have included only two ...