Javascript 如何将MongoDB文档返回到express route?
在我连接到数据库之后,我可以从一个集合中获取我的文档,但我不确定我应该如何返回它并在路由中使用它Javascript 如何将MongoDB文档返回到express route?,javascript,node.js,mongodb,express,ejs,Javascript,Node.js,Mongodb,Express,Ejs,在我连接到数据库之后,我可以从一个集合中获取我的文档,但我不确定我应该如何返回它并在路由中使用它 var findDocuments = (db, callback) => { var collection = db.collection(category) collection.find({}).toArray((err, docs) => { console.log(docs); // return "docs" array callback;
var findDocuments = (db, callback) => {
var collection = db.collection(category)
collection.find({}).toArray((err, docs) => {
console.log(docs);
// return "docs" array
callback;
})
}
app.get("/route", (res, req) => {
MongoClient.connect(url, (err, db) => {
console.log("Connected successfully")
findDocuments(db, () => {
// I WANT TO RETURN THE "docs" ARRAY SO I CAN USE IT HERE
// The ".render()" is for my templating engine
// res.render('field', {field: docs});
db.close();
})
});
})
我希望能够将“docs”数组传递到渲染,以便使用ejs(嵌入式JavaScript模板引擎)模板上的信息。您可以在回调中接受docs变量,然后在调用时传递它们。另外,由于回调是在请求的范围内定义的,因此可以从那里访问响应方法
var findDocuments = (db, callback) => {
var collection = db.collection(category)
collection.find({}).toArray((err, docs) => {
console.log(docs);
// return "docs" array
callback(docs);
})
}
app.get("/route", (res, req) => {
MongoClient.connect(url, (err, db) => {
console.log("Connected successfully")
findDocuments(db, (docs) => {
res.render(docs)
db.close();
})
});
}
您可以使用res.json(…)
发送对请求的响应
试试这个:
app.get("/route", (req, res) => {
MongoClient.connect(url, (err, db) => {
console.log("Connected successfully")
findDocuments(db, (docs) => {
res.json(docs)
db.close();
})
});
}
我得到一个错误,说res.render不是一个函数(也在res.send(docs)中尝试过,我得到了相同的错误),您可以使用“cosole.log(res)”来检查res变量上有哪些可用的方法。您还可以提供有关您使用的服务器的信息吗?它是express吗?我console.log(res)和我得到了很多东西,是的,我正在使用express。我仍然得到错误,说res.json不是函数,我认为我不允许在MongoClient.connect中使用res参数。你需要更改get route的参数,从
(res,req)
到(req,res)
req
是第一个参数,res
是第二个参数。我已经更新了我的答案,请重试。