繁体   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