Q: get data with find in mongoose and node I have a problem returning some data from a db in mongodb. I put you in situation.
I have a file called db.js, which has the following content:
const mongoose = require('mongoose');

var libro = mongoose.Schema({
        titulo: String,
        estado: String,
        autor: String,
        genero: String
});

module.exports = mongoose.model('estanteria', libro);

I have another file called estanteria.js that has the following content:
const Libreria = require('./db');
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/libreria', (err) => {
    if(err) throw err;

    console.log("Conexión a db correcta");
});

...

function allBooks(){
    var libros = Libreria.find({}) 

    return libros;
}

exports.allBooks = allBooks;

The problem I have in the function allBooks(), I do not know how to return the contents of the collection in an array of objects, and then display it on the web. Can somebody help me?

A: Inside allBooks function add a callback function to return after find operation.
function allBooks(){
    Libreria.find({}).exec(function(error, records) {
        if (!error) {
            res.send({
                success : true,
                records : records
            });
        } else {
            console.log(error);
            res.send({
                success : false,
                error : error
            });
        } 
});
}

exports.allBooks = allBooks;


A: Libreria.find({}) is an async operation, you need to use Promises way to handle this. As shown below: 
Libreria.find returns a promise and you can handle the resolve state of this promise in .then method and if any error occurs it will be done in .catch
    function allBooks(){    
        Libreria.find({}) 
           .then(function(books) {
              return books;
           })
           .catch(function(error){
              return error;
           })
    }

    // An exmaple router handler as follow:
     router.get("/posts", function(req, res){
       allBooks()
         .then(function(records){
           res.json({status: true, records})
         })
        .catch(function(error){
           res.json({status: false, error })
         });
     })


Read more about mongoose promises: http://mongoosejs.com/docs/promises.html
Promises in general: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise


A: Use JSON.stringify() to encode libros in a jhson format then write it as an response to the request ( The request recieved by the server )
