日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

mongoose多条件模糊查询实例

發布時間:2025/7/14 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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多条件模糊查询实例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。