简体   繁体   English

正则表达式在 MongoDB 中查找多个字段的匹配文档

[英]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帖子.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 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)

This will find all posts where someField and anotherField match certain regular expressions.这将找到someFieldanotherField与某些正则表达式匹配的所有帖子。

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.您还可以使用$or进行匹配,以获取匹配任一表达式的任何帖子。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过在nodejs中使用多个字段的搜索操作使用mongoose获取与mongodb中的字段匹配的所有文档 - how to get all the documents that are matching the fields in mongodb using mongoose by using search operation with multiple fields in nodejs mongoDB-如何在多个文档中查找和排序多个字段并将它们存储在单个数组中? - mongoDB - How to find and sort multiple fields in several documents and store them in a single array? 如何在一次查询中对mongodb中的多个字段和多个文档进行递增 - How to increment value in multiple fields and multiple documents in mongodb in one query 正则表达式,多次匹配一个单词 - Regexp, matching a word multiple times Mongodb 查找匹配多个正则表达式的所有文档 - Mongodb find all documents that match multiple regex's 流星/ MongoDB:按相同属性的多个值查找文档 - Meteor/MongoDB: find documents by multiple values of same property 从MongoDB和Meteor中的多个选择器元素中查找文档 - Find documents from a multiple selector element in MongoDB and Meteor 在mongodb中对多个文档进行分组 - Grouping multiple documents in mongodb 使用mongodb更新多个文档 - update multiple documents with mongodb 通过匹配数组mongodb中的字段获得$ sum - $sum by matching fields in array mongodb
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM