Issue
I have the following code:
app.get('/', async (req, res) => {
let results = await db.collection("malwarepad-website").find("6047667ff156cb8135bdaa88").toArray()
console.log(results)
res.render('index.ejs', { startText: results });
})
I want to have it console.log ONLY the Hello, and welcome to my website…: Image 1 WITHOUT the parenthesis. I found something but it console.loged this:
[ { _id: 6047667ff156cb8135bdaa88,
mainPage:
'Hello, and welcome to my website. I don\'t know how you found me but you\'re welcome :) You can find a lot of cool things, such as software, malware e.t.c.' } ]
How can I manage to archive that?
Thank you for all the answers.
EDIT: Someone’s answer in the comments:
results.forEach(r => console.log(r.mainPage));
But now how can I use pass this to a variable?
Solution
You are using Mongo’s find
method combined with the toArray()
cursor method which returns (no surprise) an array of documents.
When you "print" an array the convention in javascript/nodejs
is [ ... array content ... ]
, as in with the parenthesis.
So you have two options:
- Use
findOne
instead offind
,fineOne
returns a single document
const results = await db.collection("malwarepad-website").findOne("6047667ff156cb8135bdaa88")
console.log(results)
- Just access the array for the first / all results:
let results = await db.collection("malwarepad-website").find("6047667ff156cb8135bdaa88").toArray()
console.log(results[0])
// OR FOR MULTIPLE RESULTS //
let results = await db.collection("malwarepad-website").find("6047667ff156cb8135bdaa88").toArray()
results.forEach((result) => console.log(result))