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?
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;
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
使用JSON.stringify()
以jhson格式编码libros,然后将其作为对请求的响应(服务器接收到该请求)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.