MongoDB Stitch retrieves all data fields

Can anyone help me with my MongoDB query issue?

I've recently started working with mongoDB and I'm having trouble getting just one field back for all my documents.

var docs = db.collection("articles").find({}, { _id: 0, title:1}).asArray();

Despite specifying that I only want the "title" field in the projection, the query is returning all fields. There are no errors but I can't figure out what's wrong. Maybe someone else can spot the mistake I'm missing?

Any assistance would be greatly appreciated!

For reference, I'm using the Stitch API from mongoDB Atlas.

Answer №1

It appears that you are utilizing the MongoDB Stitch Browser SDK, specifically version 4.

In this scenario, the collection represents an instance of RemoteMongoCollection. When using find(), you can provide options in the format of RemoteFindOptions. One way to specify which fields should be included in the matching documents is by defining a projection object with relevant keys.

For demonstration:

const client = stitch.Stitch.initializeDefaultAppClient('app-id');
const db = client.getServiceClient(stitch.RemoteMongoClient.factory, 'mongodb-atlas').db('databaseName');

client.auth.loginWithCredential(new stitch.AnonymousCredential())
       .then(() => {
          db.collection('collectionName')
            .find({}, 
                  {"projection":{"_id":0, "title": 1}}
             )
            .asArray().then(docs => {
              // display results 
              console.log(docs);
          });
        }).catch(err => {
          // Manage errors here
          console.log("Error", err);
 });

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

Using a CSS style to modify a class based on another class at the same level in the hierarchy

I am working with a jQuery carousel that is adding an 'active' class to images within a div. Within the same div, there is also a span with a 'fade' class that has a CSS style of opacity: 0. Is there a way to change the CSS style of the ...

What is the best way to arrange the keys within a nested object in JavaScript?

Question: { "foo": "bar", "bar": "baz", "baz" : { "nestedKey": "foo" } } In order to sign this request using the Hmac512 algorithm, I must first stringify the object. I am concerned that if the key order is not preserved, the generated signature on the ...

Transforming a string representation of a nested array into an actual nested array with the help of JavaScript

My database stores a nested array as a string, which is then returned as a string when fetched. I am facing the challenge of converting this string back into a nested array. Despite attempting to use JSON.parse for this purpose, I encountered the following ...

The Node.js server is outputting an HTTP status code of 404

I have recently set up a small server. Interestingly, when I attempt to perform a GET request to my server through a browser, I can see the correct data. However, when I try to make a POST request to my server using code, I receive an HTTP status 404 error ...

Transferring information from a function-based module to a higher-level class component in React Native

I'm currently working on an application that has a tab navigation. One of the screens in the tab is called "ScanScreen," where I'm trying to scan a UPC number and send it to the "HomeScreen" tab, where there's a search bar. The goal is for t ...

Angular - creating a specialized input field for a unique MatDialogConfig configuration file

I have a unique setup with a custom MaterialDialogConfig file dedicated to handling all of my material dialog components. Here's what the configuration file looks like: import { MatDialogConfig } from "@angular/material"; export class MaterialDialog ...

Issue with PassportJs not forwarding users after successful authentication

I'm facing some challenges with implementing Passport for authentication. I have set up my signup strategy in the following way: passport.use('local_signup', new localStrategy({ usernameField: 'username', passwordField:&apo ...

The jQuery pop-up fails to activate on the initial click

I have multiple "Buy Now" buttons for different products. If the button is labeled as "sold-out," it should not do anything, but if it's available, it should trigger a jQuery Magnific Popup. Currently, the popup only opens after the second click becau ...

The inline filter in angularJS is failing to function as expected within the ng-repeat loop

I am currently working with angularJS version 1.2.14. Within my interface, the ng-repeat function successfully displays the information as intended. However, there seems to be an issue with the filter functionality. Despite entering text into the input bo ...

Navigating the authorization header of an API request in a Node environment

const authHeader = req.headers["authorization"]; I have a question that may come across as basic - why do we use ["authorization"] instead of just .authorization? After some research, I discovered it had to do with case sensitivity but ...

Using NodeJS and ExpressJS to send the HTTP request response back to the client

After creating a website using Angular 2 and setting up node.js as the backend, I successfully established communication between the Angular client and the node.js server. From there, I managed to forward requests to another application via HTTP. My curren ...

I have created an Express.js application. Whenever I visit a page, I consistently need to refresh in order for the variables to appear correctly

Hello, I'm seeking some assistance. Despite my efforts in searching for a solution, I have not been successful in finding one. I've developed an application using Express.js that includes a basic form in jade. The intention is to display "Yes" i ...

React encountered an error: Unable to destructure the property 'id' of '_ref' as it has been defined

After spending several hours trying to solve this issue, I am completely stuck. The console shows that the patch request successfully updates the information, but then my map function breaks, leading to a blank page rendering. Here is the problematic comp ...

A guide on successfully transferring JSON Data to an Express REST API

Currently, I am in the process of developing a REST API with Node/Express and have a query regarding the setup of the API along with integrating a JSON file. As an illustration, the JSON data that I wish to reference consists of an ID number, model, and co ...

There are occasions when ng-show and/or ng-if fail to work as expected

My Chrome extension utilizes an ng-show expression to check a variable in Chrome storage and display a large blue button if the value is zero. However, upon opening the extension, the button may not appear on the first click, requiring multiple closures an ...

Trigger a click event on a dynamically loaded button

Here's a unique twist to the usual discussions on this topic. I have a dynamically loaded button in my HTML, and I've saved the selector for it. Later on in my code, I need to trigger a click event on this button programmatically. The typical $(& ...

Tips for extracting the src attribute from a dynamically generated iframe

My dilemma stems from a function that generates an iframe with content on my website, which unfortunately I cannot control as it is loaded remotely. The function initially creates: <span id="myspan"></span> Once the JavaScript function fu ...

The Laravel Ajax Request is Returning Null

I am faced with a perplexing issue involving a toggle button that should change the status (Show/Hide). Despite sending valid data via ajax and seeing correct data in the console, the request appears empty in the controller. I've made sure to include ...

What is the most effective method for applying numerous textures or images to a single Sphere in three.js?

Just like the title says, I'm attempting to create a similar setup to what's showcased on this website: I have the images handy, but I'm currently figuring out how to arrange them all onto a single sphere. Appreciate any guidance you can o ...

Retrieving data from a database collection and performing either bulk writing or bulk updating

I have a process in place to sync users from another service into our systems. These users are stored in a collection called TempUser, which currently has around 10k documents and will continue to grow. The steps involved in updating or creating a new user ...