Unpacking a mongoose record

During my project using mongoose, I encountered a issue. I am trying to retrieve all documents that contain a specific key and value pair role: USER. Although I am able to retrieve a list of documents, I am struggling to access the values of certain fields from it, no matter what approach I take.
Here is the code snippet:

  const getUsersList = async () => {
  const users = await userModel.find({ role: USER });

  //I also attempted:
  //In each case, I receive undefined
  const users = await userModel.find({ role: USER }).userName;
  ////
  const users = await userModel.find({ role: USER }).exec();
  ////
  Document.prototype.toObject(users);
  ////
  JSON.stringify(users).userName
}

The query is successfully fetching the documents, as console.log(users) displays the retrieved documents.

    [
  {
    _id: new ObjectId("618b1a587d57e9c8e78865e1"),
    userName: 'Username1',
    name: 'Fullname1',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee8b838f8782dfae89838f8782c08d8183">[email protected]</a>',
    password: 'Password1',
    status: 'INVITED',
    role: 'USER',
    __v: 0
  },
  {
    _id: new ObjectId("618b1a6e7d57e9c8e78865e5"),
    userName: 'Username3',
    name: 'Fullname2',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec89818d8580deac8b818d8580c28f8381">[email protected]</a>',
    password: 'Password2',
    status: 'INVITED',
    role: 'USER',
    __v: 0
  }
]

Based on the mongoose documentation, it seems like I am following the correct process. It suggests converting a document to an object using toObject(), however, I am unable to find such a method available for the query in mongoose
My schema:

  const userSchema = new Schema(
  {
    userName: { type: String, unique: true, required: true },
    name: { type: String, required: true },
    email: { type: String, unique: true, required: true },
    password: { type: String, required: true },
    confirmationCode: { type: String, required: false },
    status: { type: String, required: true, default: STATUS.INVITED },
    role: { type: String, required: true, default: USER },
  },
);

Answer №1

Since it's an array, attempting to access userName directly will not be successful. You must target the particular element. Give this a shot:

const userResponse = await userModel.find({ role: USER })
const firstUserName = userResponse[0].userName

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

Include chosen select option in Jquery form submission

Facing some challenges with a section of my code. Essentially, new elements are dynamically added to the page using .html() and ajax response. You can see an example of the added elements in the code. Since the elements were inserted into the page using . ...

Utilizing JQuery to modify the element's id and trigger a function upon clicking

There is an element with a specific ID that I have changed. However, even after changing the ID and clicking on the element with the new ID, it still triggers the function associated with the old ID. $('#1st').click(function(){ $('#1s ...

What steps can I take to resolve the CLIENT_MISSING_INTENTS issue?

After diving into learning about discord.js, I've run into a bit of a roadblock. Despite trying to troubleshoot by searching online, I can't seem to resolve the issue. const Discord = require('discord.js'); // const Discord = require(&a ...

Having trouble with passing props to data() in Vue.js?

I'm facing an issue where I am unable to pass props to data() in my Vue inline template: <network-index inline-template> ... <network-list :data="networks"></network-list> ... </network-index> Inside the Index.vue file, here ...

Increase division height when mouse hovers over it

I want the height of the div to be 50px by default and change to 300px onmouseover. I have implemented this as follows: <style type="text/css"> #div1{ height:50px; overflow:hidden; } #div1:hover{ height:300px; } </style> <body> <div i ...

eslint is designed to not handle multiple package.json files

There are two package.json files in my project root folder └ app ---- /public └ /styles └ /src └ package.json └ eslintrc.json └ webpack.config.js └ server - /something └ /something ...

Preserve the height of the previous div following an AJAX request

I am currently facing an issue where I have a script that utilizes ajax to receive a response containing a cart string (html code) with items from the cart. Inside the response handler, there is another script that sets the height of each div in the cart s ...

Formik state is mysteriously reverting field values to their default state

I've encountered an issue with my form and song state while trying to add a new field called "appleMusicId". Unfortunately, every time I add this field, it seems to reset the values of timeDescription and sceneDescription. I've spent hours tryin ...

Is there a way to stop the Firebase web client from altering the error message generated by an https.onRequest function?

I am facing an issue where I cannot retrieve the original message I sent from an "https.onRequest" function in Firebase. The firebase client is rewriting the message based on the error code, making it difficult for me to recover the originally sent body or ...

Is there a way to dynamically update one input field while another input field is being modified? [HTML / JS]

I have a form with 3 input fields. One of the inputs is disabled, while the other two are enabled. The goal is to combine the values entered in the enabled fields to populate the disabled field. How can this be achieved? Is it possible for the value in th ...

Declining the request to incorporate an external website into my web platform

While checking the console errors in Google Chrome, I encountered the following error message: The page 'https://website.com' was blocked from framing because a higher-level ancestor violates the Content Security Policy directive: "frame-an ...

Find unique numbers within a specified range using NodeJS

I need to update my arts on an NFT test via OpenSea API, but I'm facing an issue where the numbers are being repeated. Is there a way to select a number within a range that does not repeat? Here is my current code: const opensea = require("opense ...

Exploring Selenium: Techniques for examining the source code of an unidentified function

I'm fairly new to using Selenium. I have come across this javascript code snippet and I am attempting to use Selenium to inspect the script, but I haven't had much luck so far. My main goal is to employ Selenium to access/inspect the script in or ...

An anomaly where a mysterious symbol appears in front of every dollar sign in an HTML document

I have a code written in AngularJS to display the amount in dollars. However, there is an unwanted " Â " character appearing before every " $ " character in the HTML. I am looking for a way to remove this character. Your help is greatly appreciated. Thank ...

Struggling to locate the ID linked to a specific ObjectId and encountering issues with the import function?

Can someone help me with this issue? Error Message: ERROR TypeError: answerID.equals is not a function I am unsure why I am getting this error. Here is the code snippet: import { ObjectId } from 'bson'; export class Person{ personID: Objec ...

Several different forms are present on a single page, and the goal is to submit all of the data at

Looking for assistance with combining Twitter and Google data entry at once. Here's the code I've developed: Please guide me on how to submit Twitter and Google details together. <html> <head> <script type="text/javascript">< ...

How to hide offcanvas navigation bar with one click in Bootstrap 5

There was an issue with a Bootstrap 5 project where the offcanvas menu would remain open after clicking on an anchor link. Is there a way to automatically close the offcanvas menu after clicking on an anchor link? <nav class="navbar fixed-top py ...

Utilizing node-json2html, generate individual HTML tables for each record

I need assistance in consolidating my JSON data into a single HTML table, instead of generating separate tables for each record through my current transformation process. var data=[{"name":"aa","mid":"12345","user":"a123","password":"a@123"},{"name":"bb" ...

Script for collapsing or expanding is non-functional

Although I am a beginner in Javascript coding, I am eager to learn more about it. I stumbled upon some tutorials on creating collapse/expand <div> blocks. After testing the code on jsfiddle, I found that it works fine there. You can find the code he ...

Prevent Repeated Data Input in an Array using JavaScript

I am facing an issue where I need to ensure that the values being inserted are not repeated when performing a push operation. Below is the snippet of code in question: addAddress: function() { this.insertAddresses.Address = this.address_addres ...