I'm using Node JS and am making a request to my MongoDB server. The problem is the 2 console logs outside of my Data.findOne() seem to be executed before the contents in the query.
Data.findOne({_id: "---"}, (err, docs) => {
item1 = docs.projects[1]
item2 = docs.projects[2]
console.log(item1)
console.log(item2)
})
console.log(item1)
console.log(item2)
This is causing errors later on in my code as it's trying to access the contents in item1 and item2 but they are undefined. It's not an issue of whether or not the object actually exists because the logs inside the function return objects, it's just that the contents of the functions are executed at the wrong time.
CodePudding user response:
You can use promise style instead of call back style.
const SomeFunction = async() => {
try {
const docs = await Data.findOne({_id: "---"}).lean()
const item1 = docs.projects[1]
const item2 = docs.projects[2]
console.log(item1)
console.log(item2)
} catch(err) {
console.log(error)
}
}
Bonus: Faster Query with lean()
