What is the process for altering the field names within a response from an express GET request?

At the moment, my express API has the following functioning code:

router.get('/Find', function(req, res, next){
    Dog.findOne({
        'Date_Time_Competed': req.query.Competed
    }).then(function(dog){
        res.send({
            'Breed': dog.breed,
            'Age': dog.ageInYears,
            'Owner': dog.owner
        })
    }).catch(next);
});

This code queries a MongoDB database to retrieve information on breed, ageInYears, and owner, returning them in JSON format under the categories Breed, Age, and Owner.

Now, I am looking to use a .find() call to retrieve multiple entries, but I am facing difficulty in changing the field names when dealing with multiple entries.

Below is my current attempt, which is functional, but I am struggling to modify the field names. (Please note: There are additional fields in the database for each entry that I do not intend to use, which is why I am not specifying certain fields).

router.get('/Find', function(req, res, next){
    Dog.find({
        'Date_Time_Competed': req.query.Competed
    }, 'breed ageInYears owner')
    .then(function(dog){
        res.send(dog);
    }).catch(next);
}); 

Any insights or suggestions on how to proceed?

Answer №1

This code snippet demonstrates how to retrieve data about dogs based on a specific date and time:

router.get('/Find', function(req, res, next){
    Dog.aggregate([
        {$match: {Date_Time_Competed: req.query.Competed}},
        {$project: {
            _id: 0,
            "Breed": "$breed",
            "Age": "$ageInYears",
            "Owner": "$owner",
        }}
    ]).then(function(dog){
        res.send(dog);
    }).catch(next);
});

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

ExpressJS refuses to wait for my promise to be fulfilled

I'm in the process of creating a search-page on my server. Whenever the endpoint is accessed and the user waits for the search function to deliver the results and display them on the page, Express somehow redirects to the 404 handler instead. An error ...

Tips for showcasing the stored value from the database in a table

This problematic table was created: http://jsfiddle.net/ofd3nox3/ I am currently facing an issue with displaying the values stored in the database for this table per user. For example, a user has specified availability on Thursdays in the morning, Friday ...

Utilizing numerous copies of a single plugin

I recently integrated a plugin called flip-carousel.js into my website and here is an example of how it looks on the site. Check out the sample implementation Now, I encountered an issue when trying to use multiple instances of the same plugin. When init ...

Invoke functions within a separate function

I am facing an issue when it comes to invoking functions within another function. Below is a snippet of the code I am working with: <script> function saveInfo() { function returnEmail() { var _e = document.getElementById("em ...

The characteristics and functions of the THREE.TransformControls

I've been attempting to utilize transformControl in my program, but due to the lack of documentation on controls at threejs.org, I find it challenging to tap into its full potential. I'm seeking information on all the properties and methods provi ...

One might encounter undefined JSON keys when attempting to access them from a script tag

During my attempts to load a specific Json using an Ajax GET request and then parsing it, I encountered an issue when trying to access the Json key from an HTML script tag, as it returned as undefined. To troubleshoot this problem, I decided to log all th ...

Using Vue.js to connect v-html to a custom CSS stylesheet

I am currently working with HTML generated by a function on an external server and I am able to preview this within a tag. Additionally, I can retrieve the CSS information in a similar manner. <template> <div v-html="html"></div ...

Is the VueJs and ChartJs combination causing the chart to be width-responsive, but not height-responsive?

I've exhausted all options, but I can't seem to make the height of my chart respond effectively. The width is behaving as expected, adjusting responsively, but the height stubbornly remains fixed at 400px. Within my primary Vue application, I i ...

In the Sandbox, element.firstChild functions properly, but it does not work in the IDE

Encountered an issue that has me puzzled. To give you some context, I attempted to create a native draggable slider using React and positioned it in the center of the screen, specifically within my Codesandbox file. The code snippet I utilized is as follow ...

JavaScript code often contains dates that are formatted in various ways

I need to perform validation in JavaScript by comparing DATES and TIME. I need to have the date in dd/MM/yyyy format, but I am unsure of the format it is currently taking. After debugging the JavaScript code, I discovered the format. The screenshot below ...

Mapping a JavaScript object to an MVC model: A comprehensive guide

I have a JavaScript object as shown below: $scope.docPropIdentityModel = { Owner: {OwnerID:"", OwnerName: ""}, }; I need to send this object to my MVC controller using an AJAX call. Let's say the controller looks like this: controll ...

Code: Ensuring URL spaces are maintained

In my Angular 4 project, I have a service with a delete API that requires two strings as parameters. Here is an example of how it looks: this.http.delete(this.url + 'api/v1/ReportingService/collectionID/'+ '45902' +'/'+' ...

Display a message on the webpage itself, not in a pop-up, when the value exceeds 1 using JavaScript

I need help with a condition involving a variable called "truecount." If this value is less than one, I would like to display an error message on the screen instead of an alert popup. Could someone assist me with this? I am new to this and don't have ...

Leveraging setter methods within knockoutjs bindings allows for efficient data manipulation

As the day comes to a close, my mind is winding down for the night. I've been diving into the world of setters when dynamically binding to Html elements and trying to wrap my head around it. While I have read through several examples, these URLs below ...

Building a game using Javascript and a database for a project

I am currently working on developing an online game using a combination of javascript and php. My main objective is to create a seamless, real-time gameplay experience without the need to constantly refresh the page. However, I have encountered a signific ...

Attempting to retrieve data from an object by utilizing an external URL, however

Upon starting the bot console, the console displays: Online with undefined/5 After 10 seconds, an error is thrown: undefined:1 [object Promise] ^ SyntaxError: Unexpected token o in JSON at position 1 This is the code snippet being used: let players clie ...

Converting a mongoDB cursor into a JSON format

I have configured a mongoDB database with an express server. I am attempting to retrieve an object that is nested inside an array within a document. Below is the route I've set up: app.get("/api/" + BLOGS_COLLECTION + "/:blogId" ...

Encode a variable into base64 using the Buffer module in node.js

Attempting to convert a variable from an HTTP parameter to base64 using node.js and Buffer. Code snippet: var http = require("http"); var url = require("url"); http.createServer(function(req, res) { var parsedUrl = url.parse(req.url, true); var que ...

${resource} and ${promise} are both returning undefined values

Encountering the following error: TypeError: Cannot call method 'then' of undefined while working with the code below: App.controller('MainCtrl', ['$scope', 'Main', 'MainFilter', function($scope, Main, M ...

Customize your Vue 3 application with custom Axios functions for handling GET, PUT,

I am looking to enhance my use of axios by customizing the get, post, and put functions. After performing the axios.create() operation, I want every subsequent get operation to include a then and catch block. import axios from "axios"; export de ...