Categories
JavaScript Answers

How to return Mongoose results from the find method?

Spread the love

To return Mongoose results from the find method, we can promisfy Mongoose.

For instance, we write

const Promise = require("bluebird");
const mongoose = require("mongoose");

Promise.promisifyAll(mongoose);

const results = await Promise.props({
  users: users.find().execAsync(),
  articles: articles.find().execAsync(),
});
res.render("profile/profile", results);

to call promisifyAll to promisify mongoose.

Then we call Promise.props with an object with the promises as values.

We call find with execAsync to return a promise with the query resylts.

Then we get the results array with the returned results.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *