mongoose多條件模糊查詢
這是今天手頭項目中遇到的一個問題,關於mongoose如何實現類似於SQL中 nick LIKE '%keyword%' or email LIKE '%keyword%' 這種多條件模糊搜索的問題。 查閱了mongoose文檔才得以實現,特此記錄一下。
主要用到了query.$or和query.$regex這兩個find參數。
其中query.$or用於實現多條件查詢,其值是一個數組。相關文檔
示例代碼:
query.or([{ color: 'red' }, { status: 'emergency' }])
query.$regex用於實現模糊查詢。相關文檔
示例代碼:
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
通過以上兩個參數就可以實現多條件模糊查詢了。以User表為例,通過輸入一個關鍵字,來匹配昵稱或者郵箱與關鍵字相近的記錄。
示例代碼:
const keyword = this.params.keyword //從URL中傳來的 keyword參數
const reg = new RegExp(keyword, 'i') //不區分大小寫
const result = yield User.find(
{
$or : [ //多條件,數組
{nick : {$regex : reg}},
{email : {$regex : reg}}
]
},
{
password : 0 // 返回結果不包含密碼字段
},
{
sort : { _id : -1 },// 按照 _id倒序排列
limit : 100 // 查詢100條
}
)
實例代碼
var local = require('./models/local')
app.get('/local/repeat', function (req, res) {
var keyword = req.query.keyword // 獲取查詢的字段
var _filter={
$or: [ // 多字段同時匹配
{cn: {$regex: keyword}},
{key: {$regex: keyword, $options: '$i'}}, // $options: '$i' 忽略大小寫
{en: {$regex: keyword, $options: '$i'}}
]
}
var count = 0
local.count(_filter, function (err, doc) { // 查詢總條數(用於分頁)
if (err) {
console.log(err)
} else {
count = doc
}
})
local.find(_filter).limit(10) // 最多顯示10條
.sort({'_id': -1}) // 倒序
.exec(function (err, doc) { // 回調
if (err) {
console.log(err)
} else {
res.json({code: 0, data: doc, count: count})
}
})
})
local.js
var mongoose = require('./db.js'),
Schema = mongoose.Schema;
var LocalSchema = new Schema({
key : { type: String }, //變量
en: {type: String}, //英文
cn: {type: String}, //中文
tn : { type: String} //繁體
});
module.exports = mongoose.model('Local',LocalSchema);
db.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
// yay!
});
module.exports = mongoose;