首页 > 解决方案 > 如何使用 mongodb MongoClient 发出 GET 请求?

问题描述

我写了一个函数:

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"))
});

问题是:它不会在邮递员中发送它作为响应。当我在 addFunction 中将返回结果更改为 console.log(result) 时,它的结果实际上会记录到控制台,所以我知道这个函数正在工作。那么为什么它不能作为 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 从未显示我在重置之前发布的参数,我认为这是因为 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);
})

标签: javascriptnode.jsmongodb

解决方案


就像@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)
    }
});

推荐阅读