简体   繁体   中英

Meteor.js Loop over an array to check if value already exists in collection documents

I can't find an answer for this. All the examples that I saw is to find for example the value 123456 of the field Number on the collection. But what I want to know if it's possible is if I can search the whole collection documents for a number inside in the array. For example, this is the FIRST document of my collection:

{
  "_id": "Qfjgftt7jLh3njw8X",
  "reference": 102020026, // Field that I want to check
  "type": "Moradias",
  "n_beds": 5,
  "price": 30000,
  "departement": "Portalegre",
  "city": "Ponte de Sor",
  "street_name": "Rua do Comércio, CE",
  "l_surface": 248,
  "is_exclusive": true
}

The client is importing a XLSX file that is converted to JSON, and added to my collection so the reference number is inserted by the client. Then I want to loop over my JSON, (there might be more than one reference) get the references imported by the client and check if those references already exists in one of my collection documents. After that I'll throw an error. I know I can do Collection.find({reference: '102020026'}) but the thing is that there can be 100+ different references in my collection.

I hope this makes sense and haven't been asnwered somewhere else.

Thanks in advance!

You might want to use the $in mongo operator ( see doc ) to find all documents by a given array:

const ids = [
  102020026,
  102021407,
  102023660,
];

Collection.find({reference: {$in: ids}});

This returns all documents, where reference matches one of the numbers, given in the ìds` array.

Here's the solution in my case:

Using the Mongo operator $in that was answered by @Jankapunkt:

  let arr = [];
    for (let c = 0; c< myJSON.length; c++) {
      arr.push(myJSON[c].reference);
  }
  if(Collection.find({reference: {$in: arr}}).count() > 1) {
    alert(`Reference ${arr} already exists`);
    throw new Error('Duplicated reference');
  }

And without the $in Mongo operator, by just using a for loop that will end up in the same thing:

for (let c = 0; c < myJSON.length; c++) {
 if (Collection.find({reference: myJSON[c].reference}).count > 1) {
    alert(`Reference ${arr} already exists`);
    throw new Error('Duplicated reference');
 }
}

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