What is the process for accessing a particular field in the data returned by the collection.find method in Expressjs and mongodb

I've been attempting to access a specific field returned from the mongodb collection.find method without success. The console.log is not displaying anything.

router.get('/buildings', function(req, res, next) {
var db = req.db;
var collection = db.get('buildings');

collection.find({buildingNO:"1"},{},function(e,docs){
     var x=docs[0].price;
     console.log(x);
    });
});

Note: I'm using monk middle-ware instead of native mongodb

Thank you!

Answer №1

Make sure to verify the error argument in the callback and ensure your return value is:

x=docs[0]...

Don't forget, it should not be:

x=doc[0]

It's quite surprising that you're not encountering an undefined variable error.

Answer №2

Utilizing the projection feature in Node.js can be very helpful.

When using projection, you provide an empty object {} as the second parameter to project all attributes.

For instance:

By projecting an object like this:

{
_id:false // or 0
}

You will exclude the _id attribute.

In this case, we are specifying to only retrieve price:

collection.find({buildingNO:"1"}, {price:1}, function(e, docs){
     var x = docs[0].price;
     console.log(x);
});

If you notice a typo on doc[0], it should actually be docs.

Explore more about db.collection.find() here.

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

Is MongoDB still displaying results when the filter is set to false?

I am currently trying to retrieve data using specific filters. The condition is that if the timestamp falls between 08:00:00 and 16:00:00 for a particular date, it should return results. The filter for $gte than 16:00:00 is working correctly, but the $lte ...

Whenever I try to update my list of products, I encounter an error message stating that the property 'title' cannot be read because it is null

I am encountering an issue with editing data stored in the database. When attempting to edit the data, it is not displaying correctly and I am receiving a "cannot read property" error. HTML admin-products.component.html <p> <a routerLink="/ad ...

Is there a way to convey a transition MUI property from a parent component to its child component in React?

My current setup involves a parent component with a button that triggers the opening of a snackBar from MUI (child component) upon click. To enhance the user experience, my teacher suggested adding a transition effect to the onClick event so that the snack ...

Tips for retrieving field values from subdocuments in an array

What is the best way to retrieve each productID in the cart from the MongoDB document below? { "_id": ObjectId("572992d6fc8b7a5c613248f6"), "userId": "0001", "fname": "Ankur", "lname": "Vishnoi", "address1": "Palam", "city": "New ...

Issue - Basic Data Protection and Unscrambling - Node.js

I have been working on some basic code to encrypt and decrypt text, but I keep encountering an error when using the .final() function of createDecipherIV. I have tried experimenting with different encodings like Binary, Hex, and base64. Node Version: &apo ...

How can JSON data objects be transmitted to the HTML side?

I created a JSON object using Node JS functions, and now I'm looking to transfer this data to the HTML side in order to generate a table with it. However, I'm encountering difficulties sending the JSON object over because of my limited experience ...

Securing Your ExpressJs API Files from Prying Eyes in Developer Tools

Typically, when I utilize developer tools in Google and choose to open an API file in a new tab, I am able to view the data as illustrated below. However, there are occasions where upon attempting the same action on certain websites, a security precaution ...

Display a PHP file's content in an iframe without revealing the file path in the source code

In my project built with Laravel, I am utilizing PDF.JS to showcase various PDF documents. To secure the pdf path, I am attempting to conceal it by passing a PHP file in the src field of an iframe. In my view: <iframe id="reader" src="http://server.de ...

Can you provide guidance on configuring Express Gateway to establish secure connections with my services?

Currently, I have set up express-gateway to connect with a backend service on my machine through a unique port. The setup is functioning properly as the gateway acts as a proxy, conducting security checks and jwt authentication. This ensures that only au ...

Serving files from a Node.js server and allowing users to download them in their browser

I am facing an issue with my file repository. When I access it through the browser, the file automatically downloads, which is fine. However, I want to make a request to my server and then serve the file result in the browser. Below is an example of the GE ...

Tips for incorporating error messages based on specific errors in HTML

In the current setup, a common error message is displayed for all errors. However, I want to customize the error messages based on the specific type of error. For example, if the password is invalid, it should display "invalid password", and for an invalid ...

Prevent overlapping of nodes and edges in a D3 force-directed layout

Check out this fascinating example at http://bl.ocks.org/mbostock/1747543: In the demonstration, Mike illustrates how to prevent nodes from colliding with each other in a graph. I'm curious if it's feasible to also prevent collisions between no ...

Complete my search input by utilizing ajax

It's only been 30 minutes since my last post, but I feel like I'm making progress with my search posts input: I've developed a model that resembles this: function matchPosts($keyword) { $this->db->get('posts'); ...

Parsing dates arriving from a Restful Service in JavaScript

When I make a Restful call, the JSON response contains dates in a strange format like this: /Date(-62135568000000)/ What is the simplest way to convert it to a normal date format like (January 10, 2016)? I have read some articles that suggest using rege ...

Attempting to invoke a function containing a promise in Javascript

Calling the function numberOfRedeems(dealId) from another function named setUpData raises an issue where the numberOfRedeems() function, which includes a promise and returns "counter", always returns as undefined when executed within the setUpData function ...

using express to display events and gatherings from external websites

I've created a simple Express application with a single function that utilizes the nodejs request and selects specific div elements. My goal is to then render this using jade. var express = require('express'); var voc = require('vocabu ...

When attempting to set a dynamic src tag for embedding a Google Map in a React application, an X-Frame-Options

I'm attempting to display a specific location using an iframe embed from Google Maps (shown below): <iframe width="100%" height="200" frameBorder="0" scrolling="no" marginHeight={0} marginWidth={0} id="g ...

Using socket.io and express for real-time communication with WebSockets

I'm currently working on implementing socket.io with express and I utilized the express generator. However, I am facing an issue where I cannot see any logs in the console. Prior to writing this, I followed the highly upvoted solution provided by G ...

Having trouble implementing a multi-level sub menu in a popup menu in Vue.js?

data: { menuItems: [{ name: 'Item 1', children: [{ name: 'Subitem 1' }, { name: 'Subitem 2' }, { name: 'Subitem 3' }] }, { ...

How can we create a two-dimensional image with random dimensions using Math.random?

I am struggling to create a variety of flowers with different sizes from an Array. The issue I'm facing is that every time I click to add a new flower, it changes the size of all existing flowers as well. What I would like is for each added flower to ...