簡體   English   中英

正則表達式在 MongoDB 中查找多個字段的匹配文檔

[英]RegExp to find matching documents in MongoDB for multiple fields

我正在嘗試通過使用正則表達式在網站博客上創建一個簡單的搜索,並將匹配的文檔查找到對象數組中。 如果我只包含一個字段名我得到結果,它工作得很好,我如何包含多個字段以在其中搜索,例如標題和內容? 這一行:

if(req.query.search) query = query.regex('title', new RegExp(req.query.search, 'i'))

帖子.js

const express = require('express')
const router = express.Router()
const Category = require('../models/category')
const Post = require('../models/post')
const { check, validationResult } = require('express-validator')

router.route('/')
.post([
    check('title').escape().trim().isLength({ min: 3 }).withMessage('Must be at least 3 chars long'),
    check('content').trim().isLength({ min: 10 }).withMessage('Must be at least 10 chars long'),
    check('summary').trim().isLength({ min: 10 }).withMessage('Must be at least 10 chars long'),
    check('category').escape().trim().isLength({ min: 24, max: 24 }).withMessage('Must be an ID'),
], async(req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(422).json({ errors: errors.array() })
    }
    try {
        if(!req.body.headImage) req.body.headImage = undefined
        const post = new Post({
            title: req.body.title,
            headImage: req.body.headImage,
            content: req.body.content,
            summary: req.body.summary,
            category: req.body.category,
        })
        const newPost = await post.save()
        res.redirect(`/post/${newPost._id}`)
    } catch {
        res.redirect('/')
    }
})
.get(async(req, res) => {
    let query = Post.find()
    if(req.query.search) query = query.regex('title', new RegExp(req.query.search, 'i'))
    try {
        const categories = await Category.find()
        const posts = await query.exec()
        const category = {}
        const page = {title: `Search for ${req.query.search}`}
        res.render('post/searchResults', {posts, categories, category, page})
    } catch {
        res.redirect('/')
    }
})

post.js 數據庫 MODEL

const mongoose = require('mongoose')

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    headImage: {
        type: String,
        default: '/uploads/image.jpg'
    },
    content: {
        type: String,
        required: true
    },
    summary: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    },
    category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category'
    },
    views: {
        type: Number,
        default: 0
    },
    active: {
        type: Boolean,
        default: true
    },
    tags: {
        type: Array
    },
    comments: [{
        date: {
            type: Date,
            default: Date.now
        },
        name: {
            type: String,
            required: [true, 'Name is required']
        },
        email: {
            type: String
        },
        body: {
            type: String,
            required: true
        }
    }]
})

module.exports = mongoose.model('Post', postSchema)

這將找到someFieldanotherField與某些正則表達式匹配的所有帖子。

Post.find({
  someField: { $regex: 'test', $options: 'ig' },
  anotherField: { $regex: '[a-z]+', $options: 'g' }
})

您還可以使用$or進行匹配,以獲取匹配任一表達式的任何帖子。

Post.find({
  $or: [
    { someField: { $regex: 'test', $options: 'ig' } },
    { anotherField: { $regex: '[a-z]+', $options: 'g' } }
  ]
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM