Как проверить данные входные значения доступны или нет? в объектах - PullRequest
0 голосов
/ 09 января 2019

Вот что я получаю от console.log(objects):

{
    "_id" : "5bb20d7556db6915846da55f",
    "gallary" : {
        "profilepic" : [
            "1",
            "2"
        ]

    }
},
{
    "_id" : "5bb20d7556db6915846da55f",
    "gallary" : {
        "profilepic" : [
            "3",
            "4"
        ]

    }
}

У меня есть один входной массив, EX: let uniqueIDs = ["0","1","10"]. Я должен проверить gallary.profilepic доступны ли данные входные значения или нет? Предположим, что недоступно означает, что я должен нажать один массив и вернуть результаты.

Мой код:

let uniqueIDs = ["0","1","10"]
db.Gallary.find()
.forEach(function(objects){
    console.log(objects);
    // Here your JS code has to come
})

Ожидаемый результат:

["0", "10"]

Ответы [ 3 ]

0 голосов
/ 09 января 2019

Вы можете собрать массив всех идентификаторов вместе (я использовал reduce в моем примере), а затем filter из всех тех элементов в UPID, которые не появляются в этом массиве.

const data = [{"_id":"5bb20d7556db6915846da55f","members":{"regularStudent":["1","2"]}},{"_id":"5bb20d7556db6915846da55f","members":{"regularStudent":["3","4"]}}];
const UPIDs = ["0","1","10"];

// Concatenate the ids in the data together
const ids = data.reduce((acc, c) => acc.concat(c.members.regularStudent), []);

// `filter` out the elements in UPIDs that aren't in the ids array
const out = UPIDs.filter(el => !ids.includes(el));

console.log(out);

Обновление для уточнения:

Вот ваш код вместе с моим:

let UPIDs = ['0', '1', '10'];

db.Groups.find().forEach(function(objects){
  const ids = objects.reduce((acc, c) => acc.concat(c.members.regularStudent), []);
  const out = UPIDs.filter(el => !ids.includes(el));  
  console.log(out);
});
0 голосов
/ 09 января 2019

Сначала я получу все значения в БД, соответствующие данным, которые вы хотите ввести (в противном случае он загрузит все записи вашей коллекции), а затем просмотрите пропущенные строки. Наконец нажмите новую запись, если необходимо.

const UPIDs = ['0','1','10'];

const entries = await db.Groups.find({
  'members.regularStudent': {
     $in: UPIDs,
  },
});

// Get the strings that are not in the DB
const missing = UPIDs.filter(x => !entries.some(y => y.members.regularStudent.includes(x)));

// Push the missing str in DB
if (missing.length) {
  const obj = new model({
     members: {
        regularStudent: missing,
     },  
  });

  // ...
}


const UPIDs = ['0', '1', '10'];

// Thx to @Andy
const entries = [{"_id":"5bb20d7556db6915846da55f","members":{"regularStudent":['1', '2']}}];

/*
const entries = await db.Groups.find({
  'members.regularStudent': {
     $in: UPIDs,
  },
});
*/

// Get the strings that are not in the DB
const missing = UPIDs.filter(x => !entries.some(y => y.members.regularStudent.includes(x)));

// Push the missing str in DB
if (missing.length) {
  console.log('Add new data for values', missing);
}
0 голосов
/ 09 января 2019

Фильтр массива UPIDs проверяет, какие его элементы не включены в regularStudent реквизит ваших members данных:

let UPIDs = ["0","1","10"];
const data = [{
    "_id" : "5bb20d7556db6915846da55f",
    "members" : {
        "regularStudent" : [
            "1",
            "2"
        ]

    }
},
{
    "_id" : "5bb20d7556db6915846da55f",
    "members" : {
        "regularStudent" : [
            "3",
            "4"
        ]

    }
}];

const regularStudents = data.map(d => d.members.regularStudent).flat();
console.log(UPIDs.filter(a => !regularStudents.includes(a)));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...