How to run multiple query in find method mongoose?

Viewed 182

I've a controller and i'm querying into find method like:

Campaign.find({'setting.types':'views','ownerId':{$ne:userId},$where:"this.expected_views>this.views.length"}).exec().then(doc=>{
    res.status(200).json({
        'message':doc
    })
})

My database is like:

{
        "setting": {
            "bill": "900",
            "dateTime": "23-3-2020",
            "expected_time": "30",
            "expected_views": "30",
            "types": "views"
        },
        "views": [
            {
                "5678908ygvhjkhgg": true
            },
            {
                "hjsgsss687sHJSjhs": true
            }
        ],
        "_id": "609b7260e798aa14f8b6b2be",
        "id": "609b7260e798aa14f8b6b2bd",
        "imageUrl": "file.jpg",
        "link": "link",
        "ownerId": "dakdjdakdadmnkdsa"
    }

After querying using my controller the response it's sending message=[] what is wrong I'm doing?

my $where:"this.expected_views>this.views.length" clause in not working..

1 Answers

From MongoDB 4.4, $where no longer supports the deprecated BSON type JavaScript code with scope (BSON type 15). The $where operator only supports BSON type String (BSON type 2) or BSON type JavaScript (BSON type 13). The use of BSON type JavaScript with scope for $where has been deprecated since MongoDB 4.2.1.

I would recommend you to use $expr, Starting in MongoDB 3.6, the $expr operator allows the use of aggregation expressions within the query language.

  • use $expr condition and $gt operator and $size to get size of array
  • $toInt convert expected_views from string to integer
Campaign.find({
  $and: [
    {
      "setting.types": "views",
      "ownerId": { $ne: userId }
    },
    {
      $expr: {
        $gt: [{ $toInt: "$setting.expected_views" }, { $size: "$views" }]
      }
    }
  ]
}).exec().then(doc => {
  res.status(200).json({ 'message': doc });
});

Playground

Related