I’ve been playing with the MongoDB methods and I found this to be a way to create a search functionality in the back end.
router.get('/search?value=', async (req, res) => { try { const posts = await Model.find({ $or: [{ 'name': new RegExp(value, 'i') }, { 'text': new RegExp(value, 'i') }] }).sort({ date: -1 }); res.json(posts); } catch (err) { console.error(err.message); res.status(500).send('Server error'); } });
If I’m not mistaken the proper way to do the same but with aggregate, I believe its something like this:
searh: async (req, res) => { try { const posts = await Model.find({ $or: [{ 'name': new RegExp(value, 'i') }, { 'text': new RegExp(value, 'i') }] }).sort({ date: -1 }); res.json(posts); } catch (err) { console.error(err.message); res.status(500).send('Server error'); } }
It might be true, it might not be; I’m not sure, I’m not that expert in using aggregate.
Leave a Reply