user19359397
user19359397

Reputation:

How to save a query from model.findOne() on a variable using mongoose

I am trying to save the results from model.findOne() on a variable for using the results on another function. But what I get on the variable is only a pending promise:

let key = Product.findOne({ name: 'keyboard' }).then(data => { return data });
console.log(key);

and what I see on mongo shell:

Promise { <pending> }

Upvotes: 2

Views: 299

Answers (1)

John Hanley
John Hanley

Reputation: 81386

key is not the result of findOne(), it is a promise. The promise has not resolved.

To make your example work, change the code:

let key = await Product.findOne({ name: 'keyboard' }).exec();

Upvotes: 1

Related Questions