mongoose多条件模糊查询实例
生活随笔
收集整理的這篇文章主要介紹了
mongoose多条件模糊查询实例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
mongoose多條件模糊查詢
這是今天手頭項目中遇到的一個問題,關于mongoose如何實現類似于SQL中 nick LIKE '%keyword%' or email LIKE '%keyword%' 這種多條件模糊搜索的問題。 查閱了mongoose文檔才得以實現,特此記錄一下。
mongodb文檔
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 = 0local.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;參考:https://smohan.net/blog/qz1etc
轉載于:https://www.cnblogs.com/coolslider/p/7832083.html
總結
以上是生活随笔為你收集整理的mongoose多条件模糊查询实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 初始html(常用标签)
- 下一篇: VC++中字符串编码处理的一些相关问题