使用 promises 在 mongodb 中查找数据
建立
首先,安装必要的包:
npm install express cors mongoose
码
然后,向 server.js
添加依赖项,创建数据库模式和集合名称,创建 Express.js 服务器,并连接到 MongoDB:
var express = require('express');
var cors = require('cors'); // We will use CORS to enable cross origin domain requests.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var app = express();
var schemaName = new Schema({
request: String,
time: Number
}, {
collection: 'collectionName'
});
var Model = mongoose.model('Model', schemaName);
mongoose.connect('mongodb://localhost:27017/dbName');
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log('Node.js listening on port ' + port);
});
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.use(function(req, res, next) {
res.status(404).send('Sorry cant find that!');
});
现在添加我们将用于查询数据的 Express.js 路由:
app.get('/find/:query', cors(), function(req, res, next) {
var query = req.params.query;
Model.find({
'request': query
})
.exec() //remember to add exec, queries have a .then attribute but aren't promises
.then(function(result) {
if (result) {
res.json(result)
} else {
next() //pass to 404 handler
}
})
.catch(next) //pass to error handler
})
假设以下文档位于模型的集合中:
{
"_id" : ObjectId("578abe97522ad414b8eeb55a"),
"request" : "JavaScript is Awesome",
"time" : 1468710551
}
{
"_id" : ObjectId("578abe9b522ad414b8eeb55b"),
"request" : "JavaScript is Awesome",
"time" : 1468710555
}
{
"_id" : ObjectId("578abea0522ad414b8eeb55c"),
"request" : "JavaScript is Awesome",
"time" : 1468710560
}
目标是在 request
键下找到并显示包含 JavaScript is Awesome
的所有文档。
为此,启动 MongoDB 并使用 node server.js
运行 server.js
:
用法
要使用它来查找数据,请在浏览器中转到以下 URL:
http://localhost:8080/find/<query>
其中 <query>
是搜索查询。
例:
http://localhost:8080/find/JavaScript%20is%20Awesome
输出:
[{
_id: "578abe97522ad414b8eeb55a",
request: "JavaScript is Awesome",
time: 1468710551,
__v: 0
},
{
_id: "578abe9b522ad414b8eeb55b",
request: "JavaScript is Awesome",
time: 1468710555,
__v: 0
},
{
_id: "578abea0522ad414b8eeb55c",
request: "JavaScript is Awesome",
time: 1468710560,
__v: 0
}]