Home > Software design >  mongoose array query construction with javascript template literals
mongoose array query construction with javascript template literals

Time:05-04

I'm using mongodb and mongoose with expressjs

My db has the following array:

_id:6262013fa90e7b533809140d
isactive:true
schedule:Array
0:Object
1:Object
2:Object
3:Object
4:Object
5:Object
6:Object
name:"whatever"
description:"describe somthing"

In my expressjs route I'm trying to build a query like this:

app.get("/getmenu",  (req, res)=>{
    let getdate = new Date()
    let getday = getdate.getDay()-1
    
     Category.find({ "schedule.1.availabletoday" : "true" }, 
        function(error, categories){   
          console.log("categories :", categories)
          res.json({"activecategories" : categories})      
 })
    
})

This does work and returned the correct results except that I need the line below to inlcude a template literal or something equivalent, let me explain:

"schedule.1.availabletoday"

I need to replace the 1 with getday value. If getday value is 0, then the query will be

"schedule.0.availabletoday"

If getday value is 2, then the query will go looking for :

"schedule.2.availabletoday"

So how do I include the getday value in my query to be like this:

"schedule.getday.availabletoday"

I tried

"schedule.${getday}.availabletoday"

but it returned empty results, by empty I mean this : []

I tried

"schedule.getday.availabletoday"

the query returned empty results : []

According to the mongodb doc, to search the array elements, I need the quotation mark around my array element query. So I can't just write this:

 schedule.getday.availabletoday

Do I need to update my node or expressjs application to be able to use template literals or is it something else I'm missing here?

CodePudding user response:

Use Template String as

`schedule.${getday}.availabletoday`

As per your example:

app.get("/getmenu",  (req, res)=>{
    let getdate = new Date()
    let getday = getdate.getDay()-1
    
     Category.find({ `schedule.${getday}.availabletoday` : true }, 
        function(error, categories){   
          console.log("categories :", categories)
          res.json({"activecategories" : categories})      
 })

CodePudding user response:

This should work for you:

let getdate = new Date();
let day = getdate.getDay()-1;
let query = {};
query[`schedule.${day}.availabletoday`] = true;

Category.find(query, (err, categories)=> {
  console.log("categories :", categories)
  res.json({"activecategories" : categories}) 
})
  • Related