Validating all data with DB before bulk insert mongoose/mongodb
<p>I am trying to validate the array of objects before inserting them into the mongodb.</p>

<p>what i am trying to do is, lets say i have an object like below</p>

<pre><code>    var data= { prodDetails: 
       [ 
         { measured: 'Liters',
           name: 'A',
           prodCode: '713',
           status: true },
         { measured: 'Liters',
           name: 'B',
           prodCode: '713',
           status: true },
         { measured: 'Liters',
           name: 'C',
           prodCode: '674',
           status: true } 
]
};
</code></pre>

<p>before making a bulk insert call i want check whether the given <code>prodCode</code> is valid DB Code or not and <code>name</code> duplicated or not</p>

<p>i am using <code>node</code> <code>bluebird</code> promises. </p>

<p>i tried the following code to validate <code>prodCode</code></p>

<pre><code>var bulkOperations = {
    bulkProdInsert: function (body) {
        return new Promise(function (reslv, rej) {
            if (body.prodDetails.length &gt; 0) {
                common_lg.getValueById(body, "typesProd", body.prodDetails[0].prodCode).then(bulkOperations.successCallback(reslv, rej, body)).catch(bulkOperations.errCallback(reslv, rej, body));
            };
            reslv();
        });
    },

    successCallback: function (reslv, rej, body) {
        return function (res) {
            if (res) {
                body.prodDetails.splice(0, 1);
                if (body.prodDetails.length &gt; 0) {
                    common_lg.getValueById(body, "typesProd", body.prodDetails[0].prodCode).then(bulkOperations.successCallback(reslv, rej, body)).catch(bulkOperations.errCallback(reslv, rej, body));
                }
            };
        };
    },

    errCallback: function (reslv, rej, body) {
        return function (err) {
            body.prodDetails.splice(0, 1);
            if (body.prodDetails.length &gt; 0) {
                common_lg.getValueById(body, "typesProd", body.prodDetails[0].prodCode).then(bulkOperations.successCallback(reslv, rej, body)).catch(bulkOperations.errCallback(reslv, rej, body));
            };
        };
    }
};
</code></pre>

<p>but i want to do is insert all the objects/documents into DB when <code>name</code> and <code>prodCode</code> of all the objects/documents is validated.</p>

<p>how to achieve this.</p>

<p>thanks</p>