【问题标题】:RegExp to find matching documents in MongoDB for multiple fieldsRegExp 在 MongoDB 中查找多个字段的匹配文档
【发布时间】:2020-06-29 16:27:18
【问题描述】:

我正在尝试使用正则表达式在网站博客上创建一个简单的搜索,并将匹配的文档查找到对象数组中。 如果我只包含一个字段名我得到结果,它工作得很好,我如何包含多个字段以在其中搜索,例如标题和内容? 这一行:

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 数据库模型

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)

【问题讨论】:

标签: javascript node.js regex mongodb mongoose


【解决方案1】:

这将找到所有 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' } }
  ]
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-25
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多