我写了一个函数:
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
在终端中,但在邮递员中显示有效的响应。在我开始重写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);
})
答案 0 :(得分:0)
就像@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)
}
});