Accessing information stored in a MongoDB database and displaying it in an AngularJS

Exploring my MongoDB repository

 import org.springframework.data.mongodb.repository.MongoRepository;

public interface RecordRepository extends MongoRepository<Record, String> {
}

Here is my model:

public class Record {

private long id;
private String cameraid;

@JsonSerialize(using=DateTimeSerial.class)
private DateTime timestamp;
private String filename;


public Record(long id,String cameraid, DateTime timestamp, String filename) {
    this.id=id;
    this.cameraid = cameraid;
    this.timestamp = timestamp;
    this.filename = filename;
} //getters and setters

Now, let's take a look at the main controller:

@RequestMapping(value="list") //controller for list
public List<Record> getList() {
        List<Record> recordList = rep.findAll(); 


        return recordList;
}
}

Reviewing the data stored in MongoDB:

{"id":1,"cameraid":"001","timestamp":"2016/06/15 15:03","filename":"e997a7321a3d2966802ba466feca69f8"},
{"id":2,"cameraid":"001","timestamp":"2016/06/15 15:03","filename":"63999edc2218f490cd883592fe5d26a1"},
{"id":3,"cameraid":"002","timestamp":"2016/06/15 15:03","filename":"9ba6722aed8aa1aae0e4545ee6d376c3"},

A glimpse at my HTML file structure:

<!DOCTYPE html>
<html ng-app='camListApp'>
...

Further details in the JavaScript file:

var camListApp = angular.module('camListApp', []);
camListApp.controller('Hello', ['$scope', '$http', function($scope, $http){
...

How do I fetch and display specific cameraid data from MongoDB using AngularJS? "http://localhost:8081/camera/list" retrieves all data on the web service. Can anyone assist me with this query?

Answer №1

Even though your code relies on the server side, here is a modified version that you can try out. While the complete server code is not provided, this snippet aims to help.

     var camListApp = angular.module('camListApp', []);
        camListApp.controller('Hello', ['$scope', '$http', function($scope, $http){
var valueA="001";
var valueB="002";
                 $http.get('http://localhost:8081/camera/list?value1='+ valueA+'&value2='+ valueB).then(function(response) {
              console.log(response);
                    $scope.records= response.data;
                });
        }]);

In the HTML select element, make sure to update it to {{records.cameraid}}

 @RequestMapping(value="list") //controller for list
    public List<Record> getList(@RequestParam("value1") String valueA, @RequestParam("value2") String valueB) {
            List<Record> recordList = new ArrayList<Record>(); 
 List<Record> valueRecordA=rep.findByCameraId(valueA);

List<Record> valueRecordB=rep.findByCameraId(valueB);
recordList.add(valueRecordA);
recordList.add(valueRecordB);
return recordList;
    }

Answer №2

It is recommended to return either an Object or a JSON string when using the rep.findAll() method, as it returns an Iterable interface. One way to achieve this is by employing JSON with the help of the Jackson ObjectMapper class:

ObjectMapper mapper = new ObjectMapper();
String output = "[]";
try {
    output = mapper.writeValueAsString(rep.findAll());
} catch (Exception e) {
    e.printStackTrace();
}
return 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

Tips on incorporating operators into mongoose

Can anyone assist me in utilizing operators such as $max and $min with mongoose? I attempted the following: User.find({Followers:max}); Unfortunately, this approach did not yield the desired results. ...

Reorganize the angular bootstrap ui modal into a factory structure

I have been working on refactoring my current code, as it has started to become unmanageable. I am using ui bootstrap for this project and came across a post that addresses a similar issue How to close Angular UI Modal from anywhere Below is the factory f ...

Tips for transferring information using '&' on websites

When using jQuery's $.ajax method to send data to add_showcase.php, an issue arises when passing a complex data structure as the "desc" parameter. The data might not be received in its entirety by the PHP file. $.ajax({ type: "GET", ...

Tips for establishing optimal parameters for an object's dynamic property

I am working with an array of objects: export const inputsArray: InputAttributes[] = [ { label: 'Name', type: 'text', name: 'name', required: true }, { label: 'User name ...

Looking to determine if a specific element is assigned multiple class names

Help needed! Can you tell me how to check if an element contains more than one classname using pure javascript, without using jQuery? For example: If #test has both the classnames "classA and classB", then { alert(true) } else { alert(false) } Here is ...

Avoid invoking function while deserializing

Is there a way to prevent a function from being called during class deserialization, such as in this scenario: private int _number public int Number { get { return _number; } set { _number = value //avoid callin ...

Modal not opening when activated from Foundation Foundation

I am encountering difficulty in triggering the Reveal modal, and I cannot figure out the issue. Initially, I suspected a JavaScript conflict. To troubleshoot, I stripped down the site to its essentials: some CSS, some JS, and some HTML. However, even afte ...

Code running successfully in Chrome's console, but encountering issues when executed on the webpage

Having some trouble assigning a function to a button in JavaScript. This is the button I'm working with, and my main goal right now is to make it responsive. <button id="artbtn" class="artbtn btn">Art</button> I experimented with this in ...

Is it possible to extract data from a JavaScript Array using scraping techniques?

I have a sample page that I want to extract data from... [ [4056, 1, 'Saturday, Aug 18 2012', '15:00', 171], [4057, 1, 'Saturday, Aug 18 2012', '15:00', 94], [4058, 1, 'Saturday, Aug 18 2012', '15:00& ...

Identifying the presence of a CSS class in order to add styling to a different element

Looking for help with CSS: /* targeting laptops */ @media only screen and (pointer:fine) and (max-device-height: 620px) { #root:has(.projects) ~ body { overflow: auto; /* allow scrolling */ } } My desired outcome is to set overflow: auto o ...

Designing versatile buttons with HTML

When accessing the website on a phone, I have trouble seeing and tapping on these two buttons because they are too far apart. I would like to change it so that once a file is selected, the 'choose file' button will be replaced by the upload butto ...

Retrieve specific information from a JSON file and save it in an array using Node.js/JavaScript

My goal is to extract all log details from a JSON object, but the issue is that the key for each user is constantly changing. let userJsonObject = { "user_1":{ "id":"user_1", "log":"de-data", ...

Fetching dynamic information via AJAX for a jQuery tooltip

I have successfully loaded content via AJAX, including a UL element with li items that each have tooltips. Now I want to load tooltip content via AJAX for each individual li item. How can I achieve this? Currently, I am making an AJAX call to load the li ...

Unravel JSON data to become PHP variables

When using angularJS ajax, I send data to a PHP file like this: { username: "someusername", password: "somepassword" } In the past, I used the following method to send data: var vars = "username="+fn+"&password="+ln; However, since angular sends da ...

What is the relationship between html, body, and window when scrolling through code?

I've been working on adding a scroll-to-top button to my website. After doing some research online, I came across this code snippet: $('html, body').animate({scrollTop:0}, 'slow'); It's interesting that they are trying to scr ...

Using AngularJS to interact with neighboring DOM elements

Imagine a scenario where there is a div containing 5 img elements. When one of these img elements is hovered over, the goal is to change the class of all the elements on its left side. <div id="stars"> <img src="star.png" data-rating="1" ng- ...

Achieving sequential actions in Javascript without the need for state updates

One aspect of jQuery that I find impressive is its ability to chain methods like .animate() and .css(). This is made possible by utilizing the special variable "this" in the backend code. I am interested in implementing a similar method chaining mechanism ...

Merging two separate observableArray into a single entity in knockout js

I am currently working on merging two distinct arrays into a general array and then connecting it using foreach. My View Model: self.cancelledItem1 = ko.computed(function () { return ko.utils.arrayFilter(self.items(), function (item) { ...

Triggering a server-side event handler in ASP.NET using client-side JavaScript

I need help with implementing a countdown timer in JavaScript. When the timer reaches 0 seconds, I would like the page to trigger the button1_click event handler. Here's the scenario: I am working on a quiz engine where the quiz responses need to be ...

Use Angular to assign a value to a radio button after it has been clicked by a button

I am working with a group of radio buttons that display different content when clicked. <div class="radio" ng-init="topRadios()"> <input type="radio" ng-model="topTable" value="topCategory" ng-change="updateTotals('topCategory')">TY ...