Updating the document array within a Mongo database using an Angular controller

I'm currently facing a challenge when it comes to inserting a new JSON object into an array of JSON objects in MongoDB from my Angular Controller.

To simplify, let's consider this schema:

var ItemSchema = new mongoose.Schema({
   id: Number,
   items: [{
      item_id: Number,
      item_name: String,
      item_price: Number
   }]
});

Inserting data into MongoDB using the Mongo console can be achieved with:

db.items.update( 
{ "_id": ObjectId("579b7860b168c80c1fe8a32a")},
{ $push: { 
    "items": {
        "item_id" : 134,
        "item_name" : "sampleItem",
        "item_price" : 234.00
    }}
})

Yet, translating this process into an http request in AngularJS is where I'm encountering difficulties. I utilized Yeoman for scaffolding and am primarily focused on creating a functional prototype at the moment. In my Angular Controller, the function being used is:

addNewItem(item, newItem) {
    this.$http.put('/api/items/' + item._id, { 'items': newItem})
      // upon success, clear the fields
     .then( response => {
        console.log(response);
        alert(this.newItem);
        item.items.push(newItem);
        newItem = {};
     });
}

Although invoking this function successfully adds the new item to my instantiated array, I'm unable to access MongoDB even though a 200 response code is returned.

In the HTML file, the following form structure exists:

<form novalidate class="condition-form">
    <fieldset> 
      <input type="number" ng-model="newItem.item_id" name="" placeholder="Enter item id">
      <input type="text" ng-model="newItem.item_name" name="" placeholder="Enter item name">
      <input type="number" ng-model="newItem.item_price" name="" placeholder="Enter item price">
      <input type="submit" ng-click="$ctrl.addNewItem(item, newItem)" value="Add">
    </fieldset> 
</form>

Deciphering how to integrate this mongodb call into my MEAN stack application has become quite perplexing. For additional context, Babel is being used alongside EMCAScript 6. Any assistance would be greatly appreciated!

Thank you

Answer №1

When the control flows to the things function in the API's backend, you'll need to utilize a MongoDB driver (such as Mongoose) for working with the mongo shell. If using mongoose, the save function would resemble this:

Things.update({'id':req.params.thing._id},{ $push : {items : req.body.items }},function (err,updated) {
if(err){
  console.log(err);
} else {
  output = {'msg':'Updated Successfully'};
}

return res.json(output); });

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

Prevent EF 6 from inserting data simultaneously when accessing the same URL multiple times concurrently

I have a web application built with ASP.NET MVC 6. When a user interacts with the client-side using Angular, I make multiple calls to ASP.NET's Async APIs in certain areas of the code to retrieve additional resources. In addition, I use Entity Framew ...

Disable vertical touchmove events to prevent scrolling vertically, while still allowing for horizontal touch and the use of buttons for scrolling

I am working on an iPad app that includes a jQuery widget with both horizontal and vertical scrolling functionality. I want to disable vertical scrolling via touch events while still allowing users to scroll vertically using buttons (such as a slider). Is ...

Arranging an array based on dates in x, y pairs for Highcharts using JavaScript or jQuery

Below is an array that I need to sort in ascending order based on the date value. var arr=[[375122780000,3],[2375122780000,4],[4375122780000,5]]; The first value in each pair represents a date in UTC format and the second value is for pressure. How can I ...

The selenium click function is successful, but it fails to locate the element on the subsequent window

I am currently working with Angularjs ui-routes and I have a link that looks like this. <a ui-sref="devs" href="#/devs"> Devs</a> This is my code snippet: from selenium import webdriver driver = webdriver.Chrome('selenium-tests/chromed ...

JavaScript validation for verifying phone numbers

Currently, I am facing an issue with my form that consists of three elements. Specifically, I am trying to implement phone number validation for the user's input. My aim is to display an alert box if the phone number field contains any characters othe ...

Changing text color based on positive or negative value in JavaScript(React)

Greetings everyone! I'm currently working on a specific feature that requires the color of a value to change dynamically. If the value is above 0, it should be displayed in green; if below 0, in red; and if equal to 0, in orange or yellow. To achieve ...

The buffering for the operation '.findOne()' has exceeded the time limit of 10000ms in Next.js with Mongoose

In my current NextJS Project, I am working on developing a newsletter application that interacts with a database called Datastax Astra. I have successfully implemented the logic to save data to the database file. However, I am experiencing a buffering issu ...

What is the correct way to set up the Suspense position within a Canvas?

Looking to adjust the position of a 3D model within a Canvas based on the x, y, and z axes? <div> <Canvas shadows dpr={[1, 2]} camera={{position: [5, 50, 5], fov: 10}}> <Suspense fallback={null}> <Model/> < ...

Searching for data in a database using jQuery UI autocomplete

Trying to implement jQuery UI autocomplete for loading a database list, but unsure of the correct method to use. Attempted the "Remote datasource" method from http://jqueryui.com/demos/autocomplete/#remote, however it was ineffective. Current code : js: ...

A comparison between Buffer.byteLength and file size

I'm facing an issue with file size discrepancies. I have a file that is reported as 51Mb in Finder, but when uploaded to the server, the byteLength of the Buffer shows a much smaller size. Could this difference be due to the file type or other propert ...

Perform the action: insert a new item into an array belonging to a model

Here is the structure of my model: var userSchema = new mongoose.Schema( { userName: {type: String, required: true}, firstName: {type: String}, lastName: {type: String}, password: {type: String, required: true}, ...

Library for visualizing JavaScript code using flowcharts and diagrams

Is there a jQuery-based javascript library available for client-side rendering and manipulation of flow-charts? I am open to other options as well. This question has been previously posed, but has not been revisited in a few years. Hopefully, there are ne ...

Strategies for optimizing progressive enhancement

Designing a website that is accessible to everyone is truly an art form, and Progressive Enhancement is something I hold dear... I am curious to hear about the best techniques you have used to ensure websites work for all users, regardless of their browse ...

Display the elements of a div at a reduced size of 25% from its original dimensions

I'm currently developing a JavaScript-based iOS simulator that allows users to view their created content on an iPhone and iPad. This involves using AJAX to load the content/page into the simulator, but one issue is that the simulator isn't life- ...

Visual Latency when Quickly Toggling Between Images in Succession

I have a series of 50 images that need to be displayed sequentially inside a div. The time interval between displaying each image is initially set at 750 milliseconds and decreases with each subsequent image. To ensure all images are loaded before the an ...

Tips for minimizing excessive repetition in your for loops

I'm currently working on developing a Chess game and I've encountered an issue with code redundancy within my Bishop class. My goal is to create a function that can determine all possible moves of a bishop on the board. In order to achieve this, ...

A condition in the JSON Schema mandates a specific field based on the value of another

How can a field be made required or non-required based on the value of another field in JSON schema? The JSON schema includes a mode field. If it is set to 'release' or 'debug', the file_path field is optional. However, if it is set to ...

Leveraging react redux in conjunction with next.js

Recently, I attempted to integrate Redux into my project using the next.js starter template from here. I successfully installed the next-redux-wrapper, however, I am having trouble locating the root file in the project. I followed the tutorial provided on ...

Load a .obj model into a variable using three.js

Just diving into the world of javascript and three.js with a question on my mind. I have successfully loaded a basic .obj file using the following code: var loader = new THREE.OBJLoader(); loader.load( 'test.obj', function ( object ) { scene. ...

Using Django to Import Data from JSON Files into a Database

Looking to import data into my model's database using JSON: { "pk": 1, "model": "companies.Company", "name": "Google", "site": "google.com" } }{ "pk": 2, "model": "companies.Company", "fields": { "name ...