'node js Mngodb print objects from level of document
I am trying to print out the formatted results of documents in my mongo db,
I can print out the top level results of the document but I cant access the lower ones
/**
* Paste one or more documents here
*/
{
"title": "Mr",
"firstName": "John",
"lastName": "Doe",
"mobile": "00000000",
"email": "[email protected]",
"homeaddress": [
{
"line1": "Calle Baja",
"line2": "Long Road",
"town": "Fake town",
"city": "Madrid",
"postecode": "D6WN7NDW"
}
],
"Shippingaddress": [
{
"line1": "Long View",
"line2": "Cave Street",
"town": "FakeTown2",
"city": "Waterford",
"postecode": "D677W4WH1"
}
],
"Orders": [
{
"Model": "Apple iPhone 13",
"purchase_date": {
"$date": "2019-04-03T20:28:46.765Z"
}
}
]
}
The above is what one of my documents looks like,
Please find below my current code which is printing out the top level doccuments _id down to email, howver I want to be able to print all the results from the selected doccument so including homeaddress, shippingaddress and Order.
const {MongoClient} = require('mongodb');
async function main() {
const uri = "mongodb+srv://.......:.............mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();
await findCustomer(client, {
findOneCustomer: 1
});
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}
main().catch(console.error);
async function findCustomer(client, {
title = "Ms",
findOneCustomer = Number.MAX_SAFE_INTEGER
} = {}) {
const cursor = client.db("phoneStore").collection("csPhoneStore")
.find({
title:title
}
)
.limit(findOneCustomer);
// Store the results in an array
const results = await cursor.toArray();
// Print the results
if (results.length > 0) {
console.log(`Found Customer with title Ms:`);
results.forEach((result, i) => {
console.log();
console.log(`_id: ${result._id}`);
console.log(`title: ${result.title}`);
console.log(`First name: ${result.firstName}`);
console.log(`Last name: ${result.lastName}`);
console.log(`mobile: ${result.mobile}`);
console.log(`email: ${result.email}`);
console.log(`homeaddress: ${result.homeaddress.line1}`);
console.log(`..........`);
});
} else {
console.log(`No Customer found`);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
