使用 Mongoose 和 Express.js 路由在 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);
});
現在新增我們將用於查詢資料的 Express.js 路由:
app.get('/find/:query', cors(), function(req, res) {
var query = req.params.query;
Model.find({
'request': query
}, function(err, result) {
if (err) throw err;
if (result) {
res.json(result)
} else {
res.send(JSON.stringify({
error : 'Error'
}))
}
})
})
假設以下文件位於模型的集合中:
{
"_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
}]