1

I am beginner in meanstack development. I am trying to push value inside an array in foreach loop but last i am getting empty array.

My code:

router.get("/", function(req, res) {

 ourpackage.find({}).sort({_id:1}).exec(function(err,resdoc){

  var rest = [];
  resdoc.forEach(function(doc){
    masterRoomimage.find({ourpackageId:doc._id},function(err,ourpackageimagevalue){
      if(err) res.send(err);
      var ourpackagedetail = JSON.parse(JSON.stringify(doc));
      var stringifyimages = JSON.parse(JSON.stringify(ourpackageimagevalue));
      var ourpackage = _.merge({},ourpackagedetail,{masterRoomimages:stringifyimages});
      rest.push(ourpackageimagevalue);
             //print all rest array value
             console.log(rest);
           });
  });
      //print empty rest array value
      console.log(rest);
      res.send(rest);
    });
});

ourpackage Schema

  {
            "_id": "58e396d4215bc61338d2c06e",
            "first_title": "test 1",
            "berief_text": "<p>testing </p>",
   }

ourpackagesimages Schema

[
            {
                "_id": "59424d49fcc8100050916bf4",
                "imageLocation": "first.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            },
            {
                "_id": "59424d49fcc8100050916bf5",
                "imageLocation": "third.jpg",
                "ourpackageId": "58e396d4215bc61338d2c077",
                "__v": 0
            },
            {
                "_id": "59490ad44e26c13324906433",
                "imageLocation": "second.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            }
    ]

expected output

[
    {
        "_id": "58e396d4215bc61338d2c06e",
        "first_title": "test 1",
        "berief_text": "<p>testing </p>",
        "ourpackagesimages": [
            {
                "_id": "59424d49fcc8100050916bf4",
                "imageLocation": "first.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            },
            {
                "_id": "59490ad44e26c13324906433",
                "imageLocation": "second.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            }

        ]
    }
]

obtained output empty

[]
1
  • Be careful: forEach is synchronous whereas find is asynchronous. I think using aggregate as shown in this answer might be useful for you. Commented Jul 7, 2017 at 13:32

2 Answers 2

0

You can't call an asynchronous function inside a synchronous function (forEach in this case). The result is accessed before it's collected and that's why the empty array output.

A very handy and easy to use library for this purpose is async. For your particular use case, map or mapLimit function will do.

var async = require('async');

router.get("/", function(req, res) {
    ourpackage.find({}).sort({
        _id: 1
    }).exec(function(err, resdoc) {

        async.mapLimit(resdoc, 5, function(doc, callback){
            masterRoomimage.find({
                ourpackageId: doc._id
            }, function(err, ourpackageimagevalue) {
                if (err) return callback(err);

                var ourpackagedetail = JSON.parse(JSON.stringify(doc));
                var stringifyimages = JSON.parse(JSON.stringify(ourpackageimagevalue));
                var ourpackage = _.merge({}, ourpackagedetail, {
                    masterRoomimages: stringifyimages
                });
                return callback(null, ourpackageimagevalue);
            });

        }, function(err, rest) {
            if(err){
                res.send(err);
            }
            else{
                res.send(rest);
            }
        });
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Hi username:@TalhaAwan I understood asynchronous and synchronous functions any another solution above mention output for merging two collection(our package collection and ourpackageimage collection)
@Senthil, are you asking another question? Sorry I didn't get it. Could you please elaborate.
thanks for your quick reply. Above I mentioned 1.ourpackages schema, 2.ourpackageimages schema, finally I want expected output.
0

simply, Declare an array rest = [];

rest[] = ourpackageimagevalue;

I hope it helps,

1 Comment

I am getting error SyntaxError:Unexpected token ]

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.