Using MEAN.JS to Define Query Parameters for Mongo from the Client Controller

I am currently developing an application using the MEAN stack - MongoDB, Angular, Express, and Node.js.

To kickstart my project, I utilized the MEAN.JS generator to set up the initial structure of my application.

The articles module within my application serves as a model for reference.

As my articles collection grows to 7000 records, each with an associated date value, I noticed a decline in performance due to loading all records into memory. To address this issue, I aim to optimize by only displaying records within the date range of (1 Month Ago) to (1 Year From Now) in a table view. Currently, I achieve this by:

In the articles.client.controller.js file:

$scope.find = function() {
        $articles = Articles.query();
};

...and within articles.server.controller.js:

var now = new Date();
var aYearFromNow = new Date(now.getTime() + 86400000*365); //add a year
var aMonthAgo = new Date(now.getTime() - 86400000*30); //subtract roughly a month

exports.list = function(req, res) { Article.find().where('date').lt(aYearFromNow).gt(aMonthAgo).sort('-created').populate('user', 'displayName').exec(function(err, articles) {
        if (err) {
            return res.send(400, {
                message: getErrorMessage(err)
            });
        } else {
            res.jsonp(articles);
        }
    });
};

However, this approach lacks flexibility. My goal is to empower users to specify their desired date ranges dynamically.

How can I establish bindings in the client view to adjust query parameters in the server controller, such as 'aYearFromNow' and 'aMonthAgo'?

Answer №1

One alternative approach is to include the search parameters directly in the query method like so:

 $scope.searchArt = function() {
    Articles.query({start:$scope.startDate, end:$scope.endDate}, function(results) {
        $scope.articles = results;
    });
};

Then, on the server-side controller, extract the query string parameters in this manner:

exports.searchForArticle = function(req, res) {
    Article.find().where('date').gt(req.query['start']).lt(req.query['end']).exec(function(error, articles) {
        if (error) {
            res.render('error', {
                status: 500
            });
        } else {
            res.jsonp(articles);
        }
    });
};

This method eliminates the need for additional routes or services.

Answer №2

To handle multiple parameters in your AngularJS application, you can create a new service or modify the existing one:

.factory('CustomService', ['$resource',
    function($resource) {
        return $resource('custom/:param1/:param2', {
            param1: '',
            param2: ''
        }, {
            update: {
                method: 'PUT'
            }
        });
    }
]);

Then, invoke this service in your controller :

$scope.fetchData = function() {
    $scope.data = CustomService.query({
        param1: $scope.firstParam,
        param2: $scope.secondParam
    });
};

On the server-side, set up a route :

app.route('/custom/:param1/:param2')
    .get(custom.getDataWithParams)

Implement a function in your back-end controller :

exports.getDataWithParams = function(req, res) {
    Data.find()
    .where('value')
    .lt(req.params.param1)
    .gt(req.params.param2)
    .sort('-created').populate('user', 'name')
    .exec(function(err, data) {
        if (err) {
            return res.send(500, {
                message: getErrorMessage(err)
            });
        } else {
            res.jsonp(data);
        }
    });
};

This approach should work for handling multiple parameters, but it's always recommended to test thoroughly.

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

Show a variety of pictures in a random arrangement?

Looking for some help here! I'm trying to shuffle my images in a random order each time the page is refreshed. It's like a game of musical chairs but with pictures! Does anyone know how to achieve this? I've done some searching, but haven& ...

Using JavaScript along with Ajax and JSON allows for sending complex data structures such as objects and

One of the features on my form allows users to input information about their clients. This versatile form enables users to add multiple phone numbers, email addresses, and physical addresses without any limitations. When adding a phone number or an email ...

Comparison of Project Structure Between Express and NestJS

I'm in the planning stages of building a REST API using Node.js for a React Native mobile app (utilizing JWT tokens) and a ReactJS web app with an admin UI that uses sessions and http-only cookies. Should I develop this directly in Express or consider ...

Troubleshooting: Dealing with Cross-Origin Resource Sharing (CORS)

I'm facing an issue with my server.js files. One of them is located inside the backend folder, and when I run nodemon server.js on localhost:3000, everything runs smoothly. I start Angular by running ng serve inside the angular folder, and logging int ...

The dialog box is not taking up the full width of the browser window

I'm facing an issue with a dialog box that only occupies a portion of the browser width, despite having a width set to 100%. The backdrop, however, extends across the entire width. //App.js import React from "react"; import ConfirmationDial ...

Every other attempt at an Ajax request seems to be successful

I'm new to using ajax and I'm having an issue with submitting a form through a post request. Strangely, the code I wrote only works every other time. The first time I submit the form, it goes through ajax successfully. However, on the second subm ...

Tips for retrieving Angular JSON data

Can someone assist me with extracting separate values from the JSON returned by an API? { ACC: "{"NO":"AC307","NAME":"joe"}, RETURN: "TRUE" } I need to retrieve the values individually, such as NO and NAME. How can I achieve this? Below is a snippet of ...

Global default configuration for CKEditor in bower: config.js

In my current Angular project, we are utilizing the angular-ckeditor module from GitHub. In order to use this module, we need ckeditor.js which was installed through bower. We have multiple pages with ckeditor instances that require the same configuration. ...

The module named 'MyApp' cannot be found or accessed

I've incorporated Angular into my MVC project. After adding the following js file and naming it MyApp.js (function () { //Creating a Module var MyApp = angular.module('MyApp', ['ngRoute']); // Will use ['ng-Route'] w ...

Is there room for improvement in this angular directive?

I have developed a custom floating label directive that extracts the value of an existing placeholder and displays it in a div element as a floating label. The placeholder attribute is then removed, and the label tag is hidden. While the directive function ...

`How to prevent Query parameters from being lost upon reloading in Nextjs Router while maintaining a clean URL structure?`

My challenge lies in sending data via router.push to a page with dynamic room id (src/pages/editor/[roomid].tsx) in Next.js. I want the URL to stay clean so users can easily edit their username in the URL if needed. When initially loaded, router.query suc ...

Flask not serving Favicon and images to a React application

I am currently working with a Flask server and have it set up in the following manner: app = Flask(__name__, static_folder="dist/assets", static_url_path='/assets', template_folder="dist") ...

How to stop empty numbers in angular.js

My goal is to ensure that an input with a required attribute always has some value, and if left empty, defaults to zero. <input ng-model='someModel' required> I have created the following directive: App.directive('input', fun ...

Axios transforms into a vow

The console.log outputs of the api and axios variables in the provided code are showing different results, with the state axios becoming a Promise even though no changes were made. The 'api' variable holds the normal axios instance while 'ax ...

My goal is to ensure that when a user copies the URL of a website from the address bar and pastes it into a social media app, the link automatically transforms into the title of

Similar to the process in Airbnb where a copied URL is pasted in Slack and replaced with specific text along with the site URL I have tried adding og:title, description, and images, but cannot figure out how to handle this issue. Any assistance would be a ...

Sending data from a partial view to a controller

Imagine I have two models: DailyTasks and Task. The initial view is strongly typed with the DailyTasks model, displaying a list of existing tasks for the day. Users can add more tasks to the list/table by clicking the add button. Upon clicking the add butt ...

Best method for creating HTML elements with jQuery

I've come across various styles and methods for creating elements in jQuery, each with its own unique approach. I am interested in discovering the most effective way to construct elements and whether a specific method stands out as superior for any pa ...

Transfer PDF file to user's web browser through XMLHttpRequest, utilizing up-to-date HTML5 techniques, all while maintaining the integrity of the document's encoding

I am trying to achieve a similar result as described in this StackOverflow post about handling file download from ajax post. However, I'm working with a dynamically-generated PDF file created using PHP v5.6.10 (with the PDFLib extension, v9.0.5). Unf ...

Ways to identify the active anchor within an li element

Below is the code snippet I am currently working with: <li> <a href="<?php echo base_url()?>home/promos/call" class="promo-call active-call"></a> </li> <li> <a href="<?php echo base_url()?>home/promos/text ...

What is the reason behind Next.js inability to import files within a directory?

Error: Module not found - Unable to locate 'components/layout' in nextjs-blog/pages/posts > 1 | import Layout from 'components/layout' 2 | import Link from 'next/link' 3 | import Head from 'next/head' I' ...