Unity of MEAN Assemblage

My current project involves working with the MEAN stack, particularly using MEAN.js. Although the documentation provides a good explanation of everything, I am facing a challenge when it comes to associating one entity or Model with another.

To give an example, generating CRUD operations for Ideas and Polls is straightforward. However, what if I need to establish a one-to-many relationship between "polls" and "ideas"?

In my polls.client.controller.js file, I believe I would do something like this:

// Create new Poll
    $scope.create = function() {
        // Create new Poll object

        var poll = new Polls ({
            ideaId: this.idea.ideaId,//here I associate a poll with an Idea
            vote1: this.vote1,
            vote2: this.vote2,
            vote3: this.vote3,
            vote4: this.vote4,
            vote5: this.vote5

        });

        // Redirect after save
        poll.$save(function(response) {
            $location.path('polls/' + response._id);

            // Clear form fields
            $scope.name = '';
        }, function(errorResponse) {
            $scope.error = errorResponse.data.message;
        });
    };

However, when the Angular model gets sent to the Express.js backend, I don't see any reference to the Idea in the request. All I receive is the Poll.

/**
 * Create a Poll
 */
exports.create = function(req, res) {
var poll = new Poll(req.body);
poll.user = req.user;
//poll.ideaId = req.ideaId;//undefined
poll.save(function(err) {
    if (err) {
        return res.status(400).send({
            message: errorHandler.getErrorMessage(err)
        });
    } else {
        res.jsonp(poll);
    }
});
};

Here is the Mongoose Model for reference:

'use strict';

/**
 * Module dependencies.
 */
 var mongoose = require('mongoose'),
Schema = mongoose.Schema;

/**
 * Poll Schema
 */
var PollSchema = new Schema({

vote1: {
    type: Number
},
vote2: {
    type: Number
},
vote3: {
    type: Number
},
vote4: {
    type: Number
},
vote5: {
    type: Number
},
created: {
    type: Date,
    default: Date.now
},
user: {
    type: Schema.ObjectId,
    ref: 'User'
},
idea: {
    type: Schema.ObjectId,
    ref: 'Idea'
}
});

mongoose.model('Poll', PollSchema);

I understand that there may be an error in my implementation, so any guidance or resources on how to accomplish this task correctly would be greatly appreciated.

Answer №1

I stumbled upon a potential solution (although I can't guarantee its accuracy or if it's just a workaround) to populate the .idea field of a poll with its corresponding ._id:

let newPoll = new Polls ({
            idea: this.idea._id,
            vote1: 5,
            vote2: 3,
            vote3: 3,
            vote4: 1,
            vote5: 2

        });

At this juncture, when I reach express, poll.idea maintains its proper association.

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

Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?

import { HttpHandler, HttpInterceptor, HttpParams, HttpRequest, } from '@angular/common/http'; import { Injectable } from '@core/services/auth.service'; import { exhaustMap, take } from 'rxjs/operators'; import { Authe ...

Executing a POST Request from AngularJS to a server-side script

Currently, I am in the process of developing a web application using Yeoman tools with AngularJS. However, I have encountered a challenge when trying to send a POST request to a server-side script from a controller. Below is the snippet of code from my con ...

Create a uniform style for the selected item in the dropdown using Handlebars Helper

Currently, I am encountering a challenge while constructing dropdowns with Handlebars. Instead of structuring the dropdown's select element in this manner: <div class="form-floating col-3"> <select name="sport" ...

How to selectively load specific scripts in index.html with the use of angular.js

Let me address a problem I'm facing with a large development project. It seems that the current setup does not function properly on Internet Explorer. My idea is to only load files that are compatible and do not generate errors when accessed through I ...

Authenticate users by accessing their login information stored in a MongoDB database using Node.js and Express

I have been experimenting with various techniques, and incorporating Passport middleware has brought me the closest to achieving this task. I suspect there might be a final step missing for everything to function correctly, as I am not encountering any err ...

Utilizing Sequelize - Establishing relationships and querying data from related tables

I have successfully implemented 3 SQL tables with Sequalize, and here are the schemas: Loans id: DataTypes.INTEGER, book_id: DataTypes.INTEGER, patron_id: DataTypes.INTEGER, loaned_on: DataTypes.DATE, return_by: DataTypes.DATE, returned_on: DataTypes.DA ...

What is the best way to change data to UTF-8 encoding using Node.js?

Working with node.js and express, I am retrieving data from MongoDB using Mongoose and sending it via res.send(data). However, I am experiencing issues with some requests where the encoding appears to be ANSI instead of utf-8 despite the header indicating ...

The AngularJS upload function is returning false when checking Request.Content.IsMimeMultipartContent

I am facing an issue while trying to upload files along with form data from my Angularjs client to a web api. I came across some reference code online and followed the same approach. However, when I execute the first line of code in the Web API method, if ...

Reading all documents from all collections in MongoDB using Express.js is a common task for developers. This guide will show

I am currently working with a MongoDB database that contains multiple documents within various collections, and I need to iterate through each of them. The code I have written for this is as follows: const mongo = require('mongodb'); const url = ...

Accessing the parent scope from a child controller in AngularJS

My controllers are set up using data-ng-controller="xyzController as vm" I am facing an issue with parent/child nested controllers. While I can easily access parent properties in the nested HTML using $parent.vm.property, I am struggling to figure out how ...

Preserving the information of a different language

What is the best method for saving a text in a foreign language with emoticons into an SQL database and then displaying it on AngularJS? The backend language being utilized is PHP, while the frontend is AngularJS. The database being used is MySQL. ...

Instructions for smoothly moving back to the top (or specific anchor) from the current view using AngularJS

As I prepare to delve into the world of Angular, a burning question comes to mind. Is it feasible to create an animation that scrolls up to the top of the page or a specific anchor point when transitioning to a new view after clicking a link while scroll ...

Is it compatible to use AngularJS with Visual Studio 2010?

I'm feeling uncertain about the performance of web applications using VS.Net 2010 and AngularJS due to the lack of posts or ideas from others. I would greatly appreciate it if someone could share their experiences. ...

Navigating Tabs the AngularJS / Bootstrap Way: Best Practices

Looking to implement tab-based navigation for a website using AngularJS and Bootstrap in the most effective manner possible. So far, I've discovered that following the guidelines of the AngularJS Seed is considered the best approach for setting up an ...

Display data in an HTML table based on user search input using Angular

I am currently working on integrating a JSON file into my project, which will eventually be accessed through an API from a server. Right now, I am pulling data directly from an object. My goal is to build an HTML file that features a table with navigation ...

Tips on ensuring Angular calls you back once the view is ready

My issue arises when I update a dropdown list on one of my pages and need to trigger a refresh method on this dropdown upon updating the items. Unfortunately, I am unsure how to capture an event for this specific scenario. It seems like enlisting Angular ...

JSON does not display the full stack trace in logs

Here is my approach to setting up log4js: import log4js from 'log4js'; const logger = log4js.getLogger(); log4js.configure({ appenders: { log: { type: 'file', filename: 'logTofile.json' } }, categories: { default: { appen ...

utilize jQuery and AngularJS to transform a JSON object into a nested JSON structure

Is there a way to convert my current JSON file into a nested JSON structure like the one below? I've attempted various methods (How to convert form input fields to nested JSON structure using jQuery), but I'm not achieving the desired outcome. Ca ...

Utilizing Nunjucks: Implementing relative file paths within HTML documents

When utilizing Flask and Jinja2, I am able to achieve the following: <link href="{{ url_for('static', filename='css/bootstrap.css') }}" rel="stylesheet" type="text/css"/> <script src="{{ url_for('static', filename=&a ...

Is CORS necessary when working with a RESTful API?

Currently in the process of constructing a RESTful API using express. Can you provide some instances where it might be necessary to implement the Cors library? In what specific scenarios would you recommend utilizing CORS with a RESTful API? ...