What is the best way to retrieve a specific number of documents from MongoDB?

I am currently facing an issue with my code that is returning all news related to a company. However, I only want the first 15 elements. Is there a way to achieve this? The following code snippet retrieves all news for a company using the google-news-json npm package.

export default async function handler(req, res) {
  try {
    let news = await googleNewsAPI.getNews(googleNewsAPI.SEARCH, req.body.companyName, 'en-US')
    res.status(200).json(news)

  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch news' })
  }
}

Answer №1

For a comprehensive understanding of google news features, it is essential to thoroughly review the API reference documentation. Within the documentation, you will come across query parameters (such as ?q=15 or ?count=no.of.items) that can be appended after your API key to specify the number of objects you wish to retrieve in the fetch URL.

Answer №2

To follow @iceweasel's advice would typically be the best course of action. However, this particular package does not have Google support and instead appears to scrape HTML from Google News directly to return results in JSON format. As a result, it lacks many standard features such as limiting the number of items returned.

If you are okay with the network cost of fetching all 100 items (which is the default behavior), you can extract the first 15 results from the API's response by using:

let top15 = news.items.slice(0, 15)

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

The solution to enabling multiple inputs when multiple buttons are chosen

Below is a link to my jsfiddle application: http://jsfiddle.net/ybZvv/5/ Upon opening the jsfiddle, you will notice a top control panel with "Answer" buttons. Additionally, there are letter buttons, as well as "True" and "False" buttons. The functionali ...

What causes the first button to be clicked and the form to be submitted when the enter key is pressed within a text

Start by opening the javascript console, then place your cursor in the text box and hit enter. What is the reason for the function "baz" being called? How can this behavior be prevented? function foo() { console.log('foo'); } function bar() ...

Tips for eliminating the trailing slash from the end of a website article's URL

I've recently delved into learning Gatsby, and I've encountered an issue with the Open Graph tag in my project. The og:image is displaying a different image than the intended thumbnail for the article. Here's an example article - . When try ...

Can anyone suggest a substitution for npm audit that involves yarn?

Looking for a way to pin resolutions using yarn while also being able to conduct an audit with npm audit? Are there any alternatives in yarn to npm audit? Alternatively, will pinning resolutions of dependencies of dependencies work in npm? ...

Manipulating binary data through the use of encodeURIComponent

Currently, I am reading a binary file by making a jQuery ajax get request. The file (a zip file in this instance) is returned as a string. After performing some actions on the file within the browser without modifying it, I need to send it back to a server ...

Instructions for turning an HTML table cell into an editable text box

Essentially, I'm looking to enable users to click on the table and edit the text within it. I found inspiration from this Js Fiddle: http://jsfiddle.net/ddd3nick/ExA3j/22/ Below is the code I've compiled based on the JS fiddle reference. I tho ...

Encountering problem with npm ERR! peer @angular/common@"^12.0.0" while trying to install @ng-bootstrap/[email protected]

Encountering an issue during the deployment of my Angular application. I added the @ng-bootstrap/ng-bootstrap package, but there seems to be a dependency resolution problem causing the issue. 22-Dec-2022 07:03:47 npm ERR! Could not resolve dependency: 2 ...

After completing the mapSeries operation, I aim to re-implement the function

How can I return queries (functions) after performing mapSeries? Any help is appreciated! async querys(querys) { const pool = await poolPromise; if (pool != null) { const transaction = new sql.Transaction(pool); ...

What options are available for managing state in angularjs, similar to Redux?

Currently, I'm involved in an extensive project where we are developing a highly interactive Dashboard. This platform allows users to visualize and analyze various data sets through charts, tables, and more. In order to enhance user experience, we ha ...

A step-by-step guide on setting up node.js and npm on Ubuntu terminal with WSL2 on Windows 10

Having trouble installing node.js and npm on my Ubuntu terminal (WSL2). I attempted to follow the instructions provided in these resources: https://learn.microsoft.com/en-us/windows/dev-environment/javascript/nodejs-on-wsl https://github.com/MicrosoftDo ...

retrieving the webpage's HTML content from the specified URL using AngularJS

Utilizing the $http.get('url') method to fetch the content located at the specified 'url'. Below is the HTML code present in the 'url': <html> <head></head> <body> <pre style = "word-wrap: break ...

What are the performance differences between using Redis strings and Redis hashes for storing JSON data?

When it comes to storing a JSON payload in Redis, there are two main methods to consider: The first method involves using simple string keys and values. key:user, value:payload (the entire JSON blob which can be 100-200 KB) SET user:1 payload The seco ...

In PATCH requests, JSON data is not transmitted through Ajax

I'm attempting to send JSON data from the client to my server with the following code: $.ajax({ url : 'http://127.0.0.1:8001/api/v1/pulse/7/', data : data, type : 'PATCH', contentType : 'application/json' ...

Choosing just the element that was clicked and added to the DOM

I've been experimenting with JQuery in a web app I'm developing. The app involves dynamically adding elements to the DOM, but I've encountered an issue with click events for these newly added elements. I'm looking for a way to target an ...

Heroku is rejecting the Discord token, but it is functioning properly in Visual Studio Code

I am facing an issue with an invalid token error on Heroku, even though the token in my main.js file on Git is the same as the one I have in Visual Studio Code. Interestingly, Heroku claims it's an invalid bot token while the Discord bot token from VS ...

What is the optimal method for implementing lazy loading in a Next.js application?

I recently read up on Lazy Loading components in the official Next.js documentation page (https://nextjs.org/learn/excel/lazy-loading-components). I followed the steps provided, but unfortunately, it didn't quite work out for me. Here's the secti ...

Display the Express response in an HTML element by utilizing the fetch API

I am currently developing a small node/express project that showcases the bcyrpt hashed value of user input. While I have been successful in displaying the hashed value in the server's console.log, I am facing difficulties in injecting this value into ...

How can we make it simple for users to update webpage content using a file from their computer?

I am developing a custom application specifically for use on Firefox 3.6.3 in our internal network. My goal is to dynamically update the content of the page based on a file stored locally on my computer. What would be the most straightforward approach to ...

Converting nested JSON structures into a PySpark DataFrame

Looking for a simple way to convert the provided JSON sample into a PySpark dataframe? Input : { "user": { "1": { "name": "Joe", "age": 28 }, "2" :{ "name": "Chr ...

What sets npm install apart from manual installation?

I've been exploring requirejs recently. I'm trying to decide between installing it using npm install requirejs or manually downloading it from the website. Are there any differences between the two methods? Are there any advantages or disadvantag ...