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

The ckeditor vanishes upon refreshing the div element

I have created two pages named openclosediv.php and content.php. The openclosediv.php page contains a list of records and a button that can show/hide the div, bringing in the content from content.php. However, I am facing an issue where the CKEditor in the ...

Steps for setting up Mongodb in NextJS upon startup

I am currently in the process of transitioning from Node/Express to NextJS, which is a Jamstack framework. However, I am facing a challenge with connecting my server to the database at startup as I used to do in Express. It seems there is no clear place to ...

In C#, how can the HTMLAgilityPack be utilized to extract a value from within a script tag?

I'm currently working with HTMLAgilityPack and I need to extract a value from a script tag. Here is the code: <div id="frmSeller" method="post" name="frmSeller"> <div class="clear"></div> <script type="text/javascript" language=" ...

Issue encountered when attempting to invoke a service from an Angular component within an office.js dialog

Our application utilizes Angular 5 and integrates Office.js to interact with Microsoft Office Word documents. Step 1: We use office displayDialogAsync to load the component. Step 2: Inside the attribute-users component, an HTTPS GET request is made to re ...

Navigate Formik Fields on a Map

Material UI text-fields are being used and validated with Formik. I am looking for a way to map items to avoid repetitive typing, but encountering difficulties in doing so. return ( <div> <Formik initialValues={{ email: '&a ...

What is the best way to retrieve all the keys from an array?

I am looking to retrieve the address, latitude, and longitude data dynamically: let Orders= [{ pedido: this.listAddress[0].address, lat: this.listAddress[0].lat, lng: this.listAddress[0].lng }] The above code only fetches the first item from the lis ...

Analyzing Compatibility and Ensuring Security

I recently started using Parse and have been exploring the documentation and answered questions. However, I still have a couple of inquiries on my mind. Firstly, I discovered that the Javascript SDK does not function on IE9 and IE8 without an SSL certific ...

What is the best way to transfer Express.js variables to MongoDB operations?

I have been developing a blogging application using Express, EJS, and MongoDB. Feel free to check out the GitHub repository for more details. One of the features I've implemented is a simple pager for the posts within the application. Within the pos ...

Sorting information in the React Native Section List

Working with React Native's SectionList and filtering data: data: [ { title: "Asia", data: ["Taj Mahal", "Great Wall of China", "Petra"] }, { title: "South America", data: ["Machu Picchu", "Christ the Redeemer", "C ...

retrieve the value of a specific key from an array

How can I extract key-value pairs from an array in JavaScript where the data is structured like this? jsonData = [ {"dimensions":[5.9,3.9,4.4,3.1,4.8],"icon":0,"curves": [false,false,false,false,false],"id":"p1","color":"0x000000"}, {"dimensio ...

Field for user input along with a pair of interactive buttons

I created a form with one input field and two buttons - one for checking in and the other for checking out using a code. However, when I submit the form, it leads to a blank page in the php file. What could be causing this issue? UPDATE After changing fro ...

broker handling numerous ajax requests simultaneously

Is there a way to efficiently handle multiple simultaneous ajax calls and trigger a callback only after all of them have completed? Are there any JavaScript libraries available that can manage numerous ajax calls to a database at the same time and execute ...

Deciphering unidentified Json data

Having some trouble with an error in my note taker app built using expressjs. Everything was working fine until I tried to save a new note and it's throwing this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () Here&apos ...

What steps can be taken to eliminate the useSearchParams() and Suspense deployment error?

I'm encountering an issue where ⨯ useSearchParams() needs to be enclosed within a suspense boundary on the page "/PaymentPage". More information can be found at: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout Although I have wra ...

Implement a callback function for unchecked checkboxes on change

Currently, I am working with a gridview that includes a checkbox field. My goal is to use jQuery to create a function that activates when an unchecked checkbox is checked. function clickAllSize() { alert("helloy"); } $(document).ready(function () { ...

What is the process for adjusting the port used by the npm run watch command?

Currently, when I run npm run watch, the development server is redirecting to http://localhost:3000 instead of http://localhost:8080. Is there a way to change the port from 3000 to 8080? I need to use Tomcat on port 8080. [BS] Proxying: http://localhos ...

"Interact with JSON data using AngularJS and JavaScript by clicking a button to edit

Here is my code in Plunker. Clicking on the Edit button should allow you to edit the details. Check out the full project here. <title>Edit and Update JSON data</title> <div> {{myTestJson.name}} <table><tbody> ...

The specified property 'slug' is not found within the designated type 'ParsedUrlQuery | undefined'

I am faced with an issue in my code where I am attempting to retrieve the path of my page within the getServerSideProps function. However, I have encountered a problem as the type of params is currently an object. How can I convert this object into a stri ...

JavaScript code using jQuery's ajax method is sending a request to a PHP server, but

Attempting to utilize jQuery ajax for PHP call and JSON return. The test is quite simple, but only receiving an empty object in response. No PHP errors appearing in the LOG File. jqXHR is recognized as an object with 'alert', yet not displayin ...

javascript accessing all data in firebase real-time database using JavaScript the right way

Working with node.js, I am retrieving data from the firebase real-time database. However, the data is being returned in the following format: Data Retrieval Code import firebaseApp from '../config.js'; import { getDatabase, ref, onValue } from & ...