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

Exploring the method to retrieve data on the server side through Express when it is shared by the client within a put request

Here is the angular http put request I am working with: sendPutRequest(data) : Observable<any>{ return this.http.put("http://localhost:5050", data).pipe(map(this.handleData)); } After making this call, the server side method being invoked is ...

Strategies for Identifying Errors in NodeJs/Express

Attempting to create a basic web service using NodeJs involves making an Ajax call like the one below: $.ajax({ type: "POST", url: "http://localhost:3800", // The JSON below is invalid and needs verification on the server side data: &apos ...

Access session value across all views in express js

Currently, I am designing a login page in express js and want to showcase the user's name on all view pages once logged in. Using session management has allowed me to display the name successfully across view pages. However, I am looking for a way to ...

Occasionally, the function XMLHttpRequest() performs as expected while other times it may

I've encountered an issue with my XMLHttpRequest() function where it randomly works in both Chrome and IE. The function is triggered by On-click, but I'm having trouble catching the error. The only information I could gather is that readystate = ...

I encountered an issue trying to reach the ExpressJS route using an href link

I am encountering a strange issue in my ExpressJS application and I'm not sure if it's a security feature or just something basic that I am overlooking. I need to directly access one of my ExpressJS routes through a regular link on the page. Whe ...

Practical strategy for developing and launching a TypeScript/Node.js application

I'm currently developing a node.js app using Typescript, which requires compilation to JS before running. As someone with a background in java/jvm, I'm hesitant about the deployment process where code is pushed to git, built/compiled on the serve ...

Issue with cookies modification in Next.js 14 server actions

I'm currently facing a challenge while working on a Next.js 14 project where I am trying to make changes to cookies. Despite carefully following the Next.js documentation regarding server actions and cookie manipulation, I keep running into an error w ...

Sending both files and JSON data in a single request using the express framework in Node.js

Below is the JADE form: <form id="formAddchallandetails" action="/adddata" method="post" name="adduser"> <input id="inputunloadingDestination1" type="text" name="finalchallan[1][unloadingDestination]" placeholder="unloading Destination"> ...

Why does my useEffect consistently execute after the initial rendering, despite having specified dependencies?

const [flag, setFlag] = React.useState(false) const [username, setUsername] = React.useState('') const [password, setPassword] = React.useState('') const [errorUsername, setErrorUsername] = React.useState(true) const [er ...

Building a dynamic URL in ReactJS from scratch

const selectedFilters = { category: "", mealtype: "lunch", cuisinetype: "Italian", dishType: "Pasta" } const apiUrl = `https://api.edamam.com/api/recipes/v2?type=public&q=${query}&app_id=${app_id}&app_key=${app_key}`; User ...

Using Javascript to deactivate a clickable image upon clicking another image

I have two buttons with alert functions assigned to each. I want the function on the first button to only work when that button is clicked, and not work if the second button has been clicked. Below is the code I've tried, but it's not functioning ...

Toggle the visibility of HTML elements by utilizing a JavaScript checkbox event

I have put together these JavaScript functions to hide the delivery address fields on my shopping cart address form if the goods are being sent to the billing address. The functions control the visibility of the HTML wrapped by... function getItem(id) { ...

Combining @angular/cli with server-side EJS templates for seamless integration

Objective: Customize Open Graph meta tags for web crawlers visiting different routes. While Angular2 4.0.0 offers a MetaService and jQuery is an option, most web crawlers do not execute Javascript except for Googlebot, making these tools somewhat ineffect ...

collaborate and coordinate a territory among various components on a map

I'm currently working with an array of elements that are being drawn on a canvas. export function useCanvas(){ const canvasRef = useRef(null); const [ elements, setElements] = useState([]); const [ isHover, setIsHover] = useState(false); ...

Mysterious dual invocation of setState function in React

My component is designed to display a list of todos like: const todosData = [ { id: 1, text: "Take out the trash", completed: true }, { id: 2, text: "Grocery shopping", completed: false }, ]; ...

Hey there everyone, I was wondering how to send both single and multiple values to a database using JavaScript and JSON endpoints with a Spring Web API

{ "id": 178, "stockin_date": "2022-11-15T08:18:54.252+00:00", "effective_date": null, "expired_date": null, "create_date": null, "update_date&q ...

Encountering errors while attempting to render MUI components in jsdom using react testing library within a mocha test

Due to the lack of maintenance and support for React 18+ in enzyme, I am faced with the task of migrating over 1750 unit tests to work with react-testing-library and global-jsdom. This migration is necessary so that our application can continue running on ...

Waiting for data to be passed from a parent component within a method

I have a situation where I need to make an API call in my layout and send the received data as an object to my component. The problem arises because the object is empty when the method is called inside the mounted() function. Therefore, I want to execute ...

After being deployed via Vercel, MongoDB faces connectivity issues with the web

After deploying my web app on Vercel, I encountered an issue where the MongoDB connection was working fine during development but failed to connect after deployment. It was suggested before deployment to reduce the function running time from 300s to 10s du ...

Manipulate Input Classes by Adding and Removing Them

I am currently using masked JS in some input fields, specifically for telephone numbers. However, I am facing an issue where phone numbers can vary in length, either 10 or 11 digits. I need to switch the class based on whether a checkbox is checked. Here i ...