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.