Как сделать запрос GET с использованием mongodb MongoClient? - PullRequest
0 голосов
/ 24 сентября 2018

Я написал функцию:

function findAll(collection) {
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost/";

    MongoClient.connect(url, function(err, db, res) {
        if (err) throw err;
        var dbo = db.db("airport");
        dbo.collection(collection).find({}).toArray(function(err, res, result) {
            if (err) throw err;
            return result;          
        });
        db.close();
    }); 
}

Который я использую в своем запросе GET:

app.get('/api/tourists', (req,res) => {
    res.send(findAll("tourists"))
});

ПРОБЛЕМА ЕСТЬ: ЭТО НЕ БУДЕТ ОТПРАВИТЬ ЕГО ОТВЕТ В ПОСТМАН.Когда я изменяю возвращаемый результат на console.log (result) в addFunction, он на самом деле регистрирует консоль, поэтому я знаю, что эта функция работает.Так почему же он не работает как HTTP-запрос?Эта функция основана на запросе POST, который похож на

function addToDb(object, collection) {
    var MongoClient = require('mongodb').MongoClient;
    var url = 'mongodb://localhost/';
    MongoClient.connect(url, object, collection, function(err, db) {
        if (err) throw err;
        var dbo = db.db("airport");
        if (object.length > 1) {
            dbo.collection(collection).insertMany(object, function(err, res) {
                if (err) throw err;
                console.log(object.length + " documents inserted");
                db.close();
            });
        }
        else {
            dbo.collection(collection).insertOne(object, function(err, res) {
                if (err) throw err;
                console.log("1 document inserted");
                db.close();
            });
        }
    }); 
}
app.post('/api/tourists', (req, res) => {
    /*
    const { error } = validateCourse(req.body);
    if (error) {
        res.status(404).send('The course with given id do not exist');
        return;
    }
    */
    const tourist = [{
        id: tourists.length + 1, 
        name: req.body.name,
        surname: req.body.surname,
        gender: req.body.gender,
        country: req.body.country,
        birthDate: req.body.birthDate,
        listOfFlightsById: req.body.listOfFlightsById

    },];
    tourists.push(tourist);
    addToDb(tourist, "tourists")
    res.send(tourist);
});

и, похоже, работает, означает, что запрос POST не показывает ничего неправильного (за исключением

Listen on port 3000 ...
the options [id] is not supported
the options [name] is not supported
the options [surname] is not supported
the options [gender] is not supported
the options [country] is not supported
the options [birthDate] is not supported
the options [listOfFlightsById] is not supported

в терминале, но этопоказывает правильный ответ в Postman. Прежде чем я начал переписывать метод GET, старый GET никогда не показывал аргументы, которые я POSTed перед сбросом, и я думал, что это потому, что GET отправлял текущий объект, а не объект из базы данных. Поэтому я хотел сделать запрос GET, который получаетего ответ прямо из mongodb

@ Trevor Varwig Я попробовал ваш код, но он не работает. Вывод такой же, как и раньше: нет ответа в Postman и нет нового запроса на левой панели, но нет ошибки в терминале.Но затем я попробовал запрос POST (который дал правильный ответ), и после этого запрос GET вызвал сбой с этой ошибкой в ​​терминале:

the options [0] is not supported
/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/operations/mongo_client_ops.js:466
      throw err;
      ^

MongoError: doc parameter must be an object
    at Function.create (/home/nedlo/node_full/expr_demo/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:43:12)
    at insertOne (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/operations/collection_ops.js:847:18)
    at executeOperation (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/utils.js:420:24)
    at Collection.insertOne (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/collection.js:463:10)
    at /home/nedlo/node_full/expr_demo/index.js:26:33
    at result (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/utils.js:414:17)
    at executeCallback (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/utils.js:406:9)
    at err (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/operations/mongo_client_ops.js:286:5)
    at connectCallback (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/operations/mongo_client_ops.js:241:5)
    at process.nextTick (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/operations/mongo_client_ops.js:463:7)
    at process._tickCallback (internal/process/next_tick.js:61:11)

ЗДЕСЬ ВСЕ КОД:

//import connect from './db.js';

//import logger from 'morgan';
const Joi = require('joi');
const express = require('express');
const app = express();
app.use(express.json());
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/airport')
const db = mongoose.connection

function addToDb(object, collection) {
    var MongoClient = require('mongodb').MongoClient;
    var url = 'mongodb://localhost/';
    MongoClient.connect(url, object, collection, function(err, db) {
        if (err) throw err;
        var dbo = db.db("airport");
        if (object.length > 1) {
            dbo.collection(collection).insertMany(object, function(err, res) {
                if (err) throw err;
                console.log(object.length + " documents inserted");
                db.close();
            });
        }
        else {
            dbo.collection(collection).insertOne(object, function(err, res) {
                if (err) throw err;
                console.log("1 document inserted");
                db.close();
            });
        }
    }); 
}

function findAll(collection, cb) {
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost/";

    MongoClient.connect(url, function(err, db, res) {
        if (err) throw err;
        var dbo = db.db("airport");
        dbo.collection(collection).find({}).toArray(function(err, res, result) {
            if (err) throw err;
            cb(result)
        });
        db.close();
    });
}

const tourists =  [
    {id: 1, name: 'Ala', surname: 'maKota', gender: 'Male', country: 'Poland', birthDate: '19.03.1993', listOfFlightsById: [1]},
    {id: 2, name: 'Ala', surname: 'maKota', gender: 'Male', country: 'Poland', birthDate: '19.03.1993', listOfFlightsById: [2]},
    {id: 3, name: 'Ala', surname: 'maKota', gender: 'Male', country: 'Poland', birthDate: '19.03.1993', listOfFlightsById: [3]},

];
//addToDb(tourists, "tourists")
//db.tourists.insert({id: 1, name: 'Ala', surname: 'maKota', gender: 'Male', country: 'Poland', birthDate: '19.03.1993', listOfFlightsById: [1]})
const flights = [
    {id:1, arrivalDate: {created: {type:Date, default:Date.now},}, departureDate: {created: {type:Date, default:Date.now},}, numberOfPlaces:15, touristsList: [""], price: "15$" },
    {id:2, arrivalDate: {created: {type:Date, default:Date.now},}, departureDate: {created: {type:Date, default:Date.now},}, numberOfPlaces:15, touristsList: [""], price: "15$" },
    {id:3, arrivalDate: {created: {type:Date, default:Date.now},}, departureDate: {created: {type:Date, default:Date.now},}, numberOfPlaces:15, touristsList: [""], price: "15$"},
];
//addToDb(flights, "flights")
//db.flights.insert({id:1, arrivalDate: {created: {type:Date, default:Date.now},}, departureDate: {created: {type:Date, default:Date.now},}, numberOfPlaces:15, touristsList: [""], price: "15$" })


app.get('/', (req, res) => {

});

app.get('/api/tourists', (req,res) => {
    findAll("tourists", function(result) {
        res.send(result)
    })
});


app.post('/api/tourists', (req, res) => {

    const tourist = [{
        id: tourists.length + 1, 
        name: req.body.name,
        surname: req.body.surname,
        gender: req.body.gender,
        country: req.body.country,
        birthDate: req.body.birthDate,
        listOfFlightsById: req.body.listOfFlightsById

    },];
    tourists.push(tourist);
    addToDb(tourist, "tourists")
    res.send(tourist);
});




app.get('/api/tourists/:id', (req,res) => {
    const tourist = tourists.find(c => c.id === parseInt(req.params.id));
    if (!tourist) return res.status(404).send('The tourist with given id do not exist');
    else res.send(tourist);

});
//PORT:
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listen on port ${port} ...`));

app.put('/api/addFlightToTourist/:id/:idT', (req, res) => {
        const tourist = tourists.find(c=> c.id === parseInt(req.params.idT))
        if (!tourist) {
            res.status(404).send('The tourist with given id do not exist');
            return;
        }
        const flight = flights.find(c => c.id === parseInt(req.params.id));
        if (!flight) {
            res.status(404).send('The flight with given id do not exist');
            return;
        }
        if (tourist.listOfFlightsById.includes(parseInt(req.params.id))) {
            res.status(404).send('The tourist is already booked for this flight');
            return;
        }
        else {
            if(flights.find(c=>c.touristsList.length === c.numberOfPlaces)) {
                res.send("Sorry, but flight is full, choose another flight id.")
                return;
            }
            else {
                tourist.listOfFlightsById.push(parseInt(req.params.id))
            }
        }
        res.send(tourist);
    })

app.delete('/api/tourists/:id', (req, res) => {
    const tourist = tourists.find(c=> c.id === parseInt(req.params.id));
    if (!tourist) return res.status(404).send("Invalid tourist id");
    const index = tourists.indexOf(touristu);
    tourists.splice(index,1);
    res.send(tourists);
})

1 Ответ

0 голосов
/ 24 сентября 2018

Так же, как @Chris G сказал в комментарии, вы возвращаетесь к своей функции toArray(), а не к функции findAll().Вам понадобится обратный звонок или обещание.Вы можете сделать что-то подобное с обратным вызовом

function findAll(collection, cb) {
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost/";

    MongoClient.connect(url, function(err, db, res) {
        if (err) throw err;
        var dbo = db.db("airport");
        dbo.collection(collection).find({}).toArray(function(err, res, result) {
            if (err) throw err;
            cb(result)
        });
        db.close();
    });
}

В своем коде веб-приложения вызовите функцию findAll с функцией обратного вызова и отправьте результат

app.get('/api/tourists', (req,res) => {
    findAll("tourists", function(result) {
        res.send(result)
    }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...