使用mongoose和node获取数据

时间:2021-08-30 18:30:30

I have a problem returning some data from a db in mongodb. I put you in situation.

我在mongodb中从db返回一些数据时遇到问题。我让你陷入困境。

I have a file called db.js, which has the following content:

我有一个名为db.js的文件,其中包含以下内容:

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:

我有另一个名为estanteria.js的文件,其中包含以下内容:

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?

我在函数allBooks()中遇到的问题,我不知道如何在对象数组中返回集合的内容,然后在Web上显示它。有人能帮助我吗?

3 个解决方案

#1


0  

Inside allBooks function add a callback function to return after find operation.

在allBooks函数中添加一个回调函数,在find操作后返回。

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;

#2


0  

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 )

使用JSON.stringify()以jhson格式对libros进行编码,然后将其写为对请求的响应(服务器收到的请求)

#3


0  

Libreria.find({}) is an async operation, you need to use Promises way to handle this. As shown below:

Libreria.find({})是一个异步操作,你需要使用Promises方式来处理它。如下所示:

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

Libreria.find返回一个promise,你可以在.then方法中处理这个promise的解析状态,如果发生任何错误,它将在.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

阅读有关mongoose promises的更多信息:http://mongoosejs.com/docs/promises.html

Promises in general: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

一般承诺:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

#1


0  

Inside allBooks function add a callback function to return after find operation.

在allBooks函数中添加一个回调函数,在find操作后返回。

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;

#2


0  

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 )

使用JSON.stringify()以jhson格式对libros进行编码,然后将其写为对请求的响应(服务器收到的请求)

#3


0  

Libreria.find({}) is an async operation, you need to use Promises way to handle this. As shown below:

Libreria.find({})是一个异步操作,你需要使用Promises方式来处理它。如下所示:

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

Libreria.find返回一个promise,你可以在.then方法中处理这个promise的解析状态,如果发生任何错误,它将在.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

阅读有关mongoose promises的更多信息:http://mongoosejs.com/docs/promises.html

Promises in general: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

一般承诺:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise