0

I have an array, using this I want to search some products. The array shown below.

 "productIds": [
   {
     "productId": ObjectId("574592dfc07f13943255c19d") 
   },
   {
     "productId": ObjectId("5745934cc07f13943255c19f") 
   },
   {
     "productId": ObjectId("57459397c07f13943255c1a1") 
   } 
 ] 

using this productId I want to search particular products. I have written some query but it takes only first productId and it's not taking remaining.

router.post('/getItemOfWishList', function(req,res){
    var wId = ObjectId(req.body.wID);
    var findwishlists = function(db, callback) {
        var cursor =db.collection('wishlists').find({_id: wId}).toArray(function(err, docs){
            if(err){  
                callback(new Error("Some problem"));
            }else{
                callback(null,docs);
            } 
        });
    };

    MongoClient.connect(config.database, function(err, db) {
        assert.equal(null, err);
        findwishlists(db, function(err,docs) {
            db.close();

            //console.log(docs[0].productIds);//It contains that array.


            for(var key in docs){
                console.log(docs[key].productIds[key].productId);
                var pID = ObjectId(docs[key].productIds[key].productId);

                var findproducts = function(db, callback) {
                    var cursor =db.collection('proInfo').find({_id: pID}).toArray(function(err, docs){
                        if(err){  
                            callback(new Error("Some problem"));
                        }else{
                            callback(null,docs);
                        } 
                    });
                };

                MongoClient.connect(config.database, function(err, db) {
                    assert.equal(null, err);
                    findproducts(db, function(err,docs) {
                        db.close();
                        if(err) return res.json({result:null})
                        else
                        return res.json({result: docs});
                    });
                });                 
            }
        });
    });
});
2
  • return res.json({result: docs}); line is stopping the loop I think. Why you are doing return? Commented Jun 27, 2016 at 13:32
  • return for to get result from node.js to angular controller. Commented Jun 27, 2016 at 13:34

1 Answer 1

3

There are a couple of issues here:

  1. The asynchronous flow of the program is incorrect - the for statement starts a bunch of asynchronous tasks and you are not waiting for all of them to complete.

  2. You are sending the response back as soon as you receive the first result - you are writing to the response as soon as the findProducts is called the first time.

You can address all these issues by utilizing the $in MongoDb operator:

MongoClient.connect(config.database, function(err, db) {
    db.collection('wishlists').find({_id: wId}).toArray(function(err, wishlist) {
      var productIds = wishlist.productIds.map(function(product) {
         return product.productId;
        });
      
      db.collection('products').find({_id: {$in: productIds}}).toArray(function (err, products) {
        return res.json(products);
      });
    });
});

You should, of course, handle all the unexpected errors and rework the snippet in order for it to fit your case more precisely.

I'd also recommend reading up a bit more on how node.js handles asynchronous work and on flow control as you are assuming that all the code will be done synchronously - one after the other. A good place to start would be: https://blog.risingstack.com/node-hero-async-programming-in-node-js/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.