Access all the properties of an object within a mongoose record

My database contains a collection of documents that are structured using the mongoose and express frameworks. Each document follows this schema:

const userSchema = new Schema({
    firstName: { type: String },
    lastName: { type: String },
    email: { type: String },
    books: { type: Object },
});
const User = mongoose.model('User', userSchema);

export default User; Inside the "books" object, each document can have various pairs of "key:value" combinations.

For instance, First document:

{
    "firstName": "Lucy",
    "lastName": "Red",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ee2fbedf7a0fcebeacee3efe7e2a0ede1e3">[email protected]</a>",
    "books": {
        "Harry Potter" : "horrible",
        "Hunger Games" : "beautiful"
     }
}

Second document:

{
    "firstName": "Tom",
    "lastName": "Brown",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0d4cfcd8ec2d2cfd7cee0cdc1c9cc8ec3cfcd">[email protected]</a>",
    "books": {
        "The Great Gatsby" : "beautiful",
        "Frankenstein" : "horrible"
     }
}

I am interested in querying the db collection to retrieve all possible keys found within the "books" objects as an array.

In this case, I aim to obtain:

["Harry Potter", "Hunger Games", "The Great Gatsby", "Frankenstein"];

Is there any way to achieve this? Thank you.

Answer №1

Give this a try:

db.collection.aggregate([
    {
        
         $project: {
            books: { $objectToArray: "$books" }
         }
      
    },
    {
        $unwind: "$books"
    },
    {
        $group: {
            _id: null,
            books: { $push: "$books.k"  }
        }
    }
])

Here is the expected result:

{
    "_id" : null,
    "books" : [
        "Harry Potter",
        "Hunger Games",
        "The Great Gatsby",
        "Frankenstein"
    ]
}

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

Node.js script terminated: Process concluded with an exit code 139 due to being interrupted by signal 11 (SIGSEGV)

I'm encountering a frustrating issue with my script - it keeps crashing and the debugger isn't able to pinpoint the error. I've attempted using try-catch blocks, but they just don't seem to work. Any recommendations on how I can better ...

Utilize Javascript to Populate Form Fields Based on "Selected Name"

I am currently facing a challenge in using javascript to automatically populate a form, specifically when it comes to setting the value for the country field. <form action="/payment" method="post" novalidate=""> <div class="input_group"> ...

Tips for dodging drawn-out sequences of periods

When working with nested objects using dot notation, it can be tedious to constantly check if each previous object exists. I'm looking for a solution that avoids lengthy if chains like if (a && a.b && a.b.c && a.b.c[0] ... ) ...

Having difficulty grasping the concept behind the prepend method's functionality

I encountered an issue with my code, where I successfully created a <th> element initially, but faced problems when trying to create it repeatedly. function createTH(){ var noOfRow = document.getElementById("addItemTable").rows.length; var t ...

Using webpack-dev-middleware in combination with create-react-app

In my React/Node application, I have implemented webpack-dev-middleware and webpack-hot-middleware on the Node side to achieve automatic bundle reload when client files change. Additionally, I use nodemon to automatically reload the server when there are ...

Avoid deleting a row in Sequelize if it is referenced in another association

Is there a method in Sequelize.js to trigger an exception when attempting to delete a row that is associated with another entity? For example, consider tables for Roles and Users. They have a many-to-many association, allowing any user to have multiple ro ...

Rails MultiSelect Array not converting to String Correctly

I am having trouble converting my array to a string properly. I am using rails multiselect: Views: <%= f.select :foo, [ ['a'], ['b'], ['c'] ], {:prompt => "Select an alpha"}, {:multiple => true} %> Controller: ...

Encountering difficulties linking to a stylesheet or a script in an HTML file delivered by Express server

Currently, I'm facing the challenge of breaking down my Express app code into multiple files. Unfortunately, I am unable to utilize <link href> or <script src> for linking stylesheets or scripts. Below is the relevant snippet from my inde ...

Accessing data outside of the scope when looping through items in Angular forEach

I am currently working on retrieving the Game ID generated by the APIService.postData method for the game. The goal is to utilize this Game ID within the Angular foreach loops to maintain foreign key constraints on the RESTful side. Any advice on extracti ...

The behavior of AngularJS checkbox and ng-change is definitely puzzling

I am facing an issue with my array structure: { key : 'abc', color: 'Red', show: true } <div ng-repeat="x in myArray"> <input type="checkbox" ng-model="x" ng-change="changeShow($index)" checked="checked" /> ...

Employing global variables in Express.js is a common practice that can provide

I have a situation where I need to access variables from one router in another router. Would using a middleware be the most efficient way to achieve this, and if so, how would I implement it? Alternatively, if I simply declare global variables at the sta ...

Embed a local page into an HTML file using PhoneGap

I attempted to load a page within my phonegap application using Jquery .load(), but it isn't functioning because it's on a local machine rather than a server. When I eventually upload the app to PhoneGap Build, my page will still be located in th ...

Retrieve data from a JSON file to assign to a variable, then access another API to retrieve a second

I am completely new to the world of javascript and json. My previous experience with javascript was quite minimal, about 12 years ago. So, please bear with me as I try to explain my current issue. The problem I am facing involves retrieving a second API UR ...

Differences Between Android and JavaScript: Ensuring Library Validity

Validation in JS is provided by the validator library which can be found at https://www.npmjs.com/package/validator Is there an equivalent library for validation in Android? If so, what is the name of Android's library? ...

The execution of events.js failed at line 136, causing an unhandled 'error' event to be thrown

Why do I keep getting events.js:136 throw er; Unhandled 'error' event and how can I fix it? I have already tried reinstalling both nodejs and mongodb, but the error persists. package.json { "name": "bookstore", "version": "1.0.0", "description" ...

Limiting the rate at which a function can be executed in NodeJS

I am facing an issue where I need to create an interval of five seconds during which a function can be executed. The reason for this is because I am monitoring an Arduino serial port, which sends multiple signals when a button is pressed. However, in my no ...

How to showcase information stored in Firebase Realtime Database within an Ionic application

Looking to list all children of "Requests" from my firebase realtime database in a structured format. Here's a snapshot of how the database is organized: https://i.stack.imgur.com/5fKQP.png I have successfully fetched the data from Firebase as JSON: ...

Requirements for adding information to a database table

I'm new to JavaScript and facing an issue that I need help with. I am trying to insert data into a database table based on certain conditions in my code, but even though I receive an error message when I input incorrect values, the data still gets ins ...

The server is responding with a 400 error code when a body is included in a

Question: I am experiencing an issue with my Express GET route that fetches all users. Each time a req.body is present, the server consistently returns a response code of 400. I am using body-parser, but this problem only occurs in the production k8s envi ...