Reputation: 38
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)
Upvotes: 0
Views: 1501
Reputation: 1889
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' } }
]
})
Upvotes: 1