您如何从服务器上的集合中获取多条信息?
问题描述:
这是我的一些代码
server.get("/get", getCallback);
function getCallback(req,res) {
collection.find({}).next(findCallback);
function findCallback(err,foundRecord) {
if (err == null) {
console.log('FOUND: ' + foundRecord);
return res.status(200).send(foundRecord);
}
else
throw err;
}
}
这让我回到了控制台中的 {"readyState":1}
.
It give's me back {"readyState":1}
in the console.
无论我尝试什么,它都会给我带来不同类型的错误.我没有将数据保存到集合中的问题,但是很快在我将其取出时,没有任何效果.
No matter what I try it's giving me different types of errors. I have no problem-saving data to the collection but as soon as I go to take it out nothing works.
答
使用 express
, get
路由采用以下形式:
Using the express
the get
route takes the form:
server.get('/', function (req, res) {
res.send('your response document...')
})
您要在浏览器中的以下位置显示一组MongoDB集合文档(快递服务器正在侦听端口3000): http://localhost:3000/get
You want to display a set of MongoDB collection documents in the browser at (the express server is listening on port 3000): http://localhost:3000/get
// Server
const express = require('express');
const server = express();
const port = 3000;
server.listen(port, () => console.log('App listening on port ' + port));
// MongoDB client
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true } );
// Your get request
server.get('/get', function (req, res) {
client.connect(function(err) {
assert.equal(null, err)
console.log('Connected to MongoDB server on port 27017')
const db = client.db('test')
const collection = db.collection('collectionName')
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null)
console.log('Found the following documents:')
console.log(docs)
res.send(docs)
client.close()
} )
} )
} );