Home » Javascript » mongo Query to return all array values and pass it to a variable to execute another query which is not returning the correct output

mongo Query to return all array values and pass it to a variable to execute another query which is not returning the correct output

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have following code in nodeJs where i am trying to query mongodb with an array of fields but it is returning me blank not sure what is going wrong:

Here is my code:

collectionA.distinct('QuoteId', (err, res) => {
if (err) {
    // register error
} else {
    var QuoteId = res;
  var quoteItems={$and: [{"created" : {$lte: new Date(new Date().setDate(new 
 Date().getDate()- 40))}},{"id": {$in:QuoteId}},{ $where: "this.items.length 
 > 0" }]}

 collection.find(quoteItems,{"items":1,_id:0}).toArray((err, res) => {
 if (err) {
    // register error
 } else {
        var quoteItems = res;
        console.log(res)
    //var query = {$and: [{"created" : {$lte: new Date(new 
 Date().setDate(new Date().getDate()- purgeDays))}}, {"id": {$in:QuoteId}}]}
    var query = {"id": {$in:quoteItems}

    collectionC.find(query,{"id":1,_id:0}).limit(10).toArray((err, doc) => {

When I printed the quoteitems, its value is coming like below, i think that’s the issue as next query is expecting only array of strings.

[ { items: [ '8218363d-bff8-411c-ae6f-c06918b9a63a' ] } ]

Issue is somewhere in the below query as it is printing the array of array:

  var quoteItems={$and: [{"created" : {$lte: new Date(new Date().setDate(new 
  Date().getDate()- 40))}},{"id": {$in:QuoteId}},{ $where: 
 "this.items.length > 0" }]}

Kindly let me know what i am doing wrong here?

Answers: