简体   繁体   中英

RegExp to find matching documents in MongoDB for multiple fields

I am trying to create a simple search on website-blog by using regex and find matching documents into an array of objects. It works just fine if I include only one fieldname I get the result, how can I include multiple fields to search within for example title AND content? This row:

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

posts.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 DB 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)

This will find all posts where someField and anotherField match certain regular expressions.

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

You can also match using $or , to get any posts matching either expression.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM