0

I watched a taptracker website tutorial, and he made an SQL database.
However, I made a MongoDB database for that site and this is it:

MongoDB songs data

So I made a search bar in my site, and I want it to search with req.params that match to any field in song [album or title or artist].

I have the MySQL code that made the same thing, but I want MongoDB code that made that.

My aim is to convert that MySQL code to MongoDB.

MySQL code

  async index (req, res) {
   try {
     let songs = null
     const search = req.query.search
     if (search) {
       songs = await Song.findAll({
         where: {
           $or: [
             'title', 'artist', 'genre', 'album'
           ].map(key => ({
             [key]: {
               $like: `%${search}%`
             }
           }))
         }
       })
       res.send(songs)
     } else {
       const songs = await Songs.find({}).limit(10)
       res.send(songs)
     }
   } catch (err) {
     res.status(500).send({
       error: 'an error has occured trying to fetch the songs'
     })
   }
 },
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71

0 Answers0