简体   繁体   中英

how to compare objects values in 2 identical lists in javascript

i have two collections in mongo db that hold reports, in report there is list matches, so what i want is to run on production reports and for ech one check in staging reports and check that if the matches are the same length if the personId and addressId are also the same...

is there aa good way to do this?

i came up with something like this:

db.production_reports.find({}).forEach((prodRep)=> { 
      db.reports.find({_id: prodRep._id}).forEach((stagingRep)=> { 
         if (prodRep.matches.length == stagingRep.matches.length) {
             prodRep.matches.forEach((match)=> {
                 var res = stagingRep.matches.filter(element => element.personId == match.personId && element.addressId == match.addressId);
                 if (res) {
                     print("yay")
                 } else {
                     print("nay")
                 }
             });
         }
      });
});

i want for each report the script to tell me "yes, all matches equal", or print the reportId that have non equal matches

thanks

I would draft something like this :

return new Promise((resolve) => {
  const data = {
    // contains an array of _id of missing production_reports
    missing: [],
    different: [],
  };

  // Look at each entry in production_reports
  db.production_reports.find({})
    .cursor()
    .eachAsync(async (x) => {
      // get the similar data on reports
       const copy = await db.reports.find({
         _id: x._id,
       });

       // If the data doesn't exists into reports
       if (!copy || !copy.length) {
          data.missing.push(x._id);

          return;
       }

       // If it exists, compare the inner values

       // if the size isn't the same, it's obviously different
       if (x.matches.length !== copy.length) {
         data.different.push(x._id);

         return;
       }

       // Check every element of match one by one
       if (x.matches.some(y => !copy.matches.some(z => z.personId === y.personId))) {
          data.different.push(x._id);
       }
    }, {
      // How many items do we look at same time
      parallel: 250,
    }, () => {
      // When we are done processing all items
      resolve(data);
    });
});

NOTE : It won't give you missing documents that exists in reports but not in production_reports

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM