A
A
asfhn2020-09-13 11:41:35
Node.js
asfhn, 2020-09-13 11:41:35

How to find a user who has objects with the same id in the array of objects?

There is a user

{
 id: 1,
 items: [{
  id: 124,
  price: 1
 },{
  id: 31
  price: 1
 },{
  id: 32,
  price: 1
 }]
}

and there is an array And you need to find a user through User.findOne () who has all the elements from the id array in items? Is it possible to do this or just find the user by id and check it yourself. I just don’t know how best to do it right away when requesting, or already cycle through the resulting array
ids = [32, 124]

Answer the question

In order to leave comments, you need to log in

3 answer(s)
H
hzzzzl, 2020-09-13
@asfhn

https://docs.mongodb.com/manual/reference/operator...
try
User.findOne({ 'items.id': { $all: ids } })

A
Alexey, 2020-09-13
@Azperin

var users = [
  {
    id: 1,
    items: [
      { id: 124, price: 1 },{ id: 31, price: 1 },{ id: 32, price: 1 },
    ],
  },
  {
    id: 2,
    items: [
      { id: 345, price: 1 },{ id: 2, price: 1 },{ id: 166, price: 1 },
    ],
  },
];

function usersFindOne(itemsArr) {
  return users.find(u => {
    return u.items.every(item => itemsArr.includes(item.id));
  });
};

console.log(usersFindOne([124, 32, 31]));
console.log(usersFindOne([345, 111, 166, 2]));

I would do something like this, if it doesn't matter if there are "extra" id in the array

A
Alexander, 2020-09-13
@Alexandre888

I just don’t know how best to do it right away when requesting it, or already cycle through the resulting array

built a bicycle with a cycle:
let obj = {
  id: 1,
  items: [{
    id: 124,
    price: 1
  }, {
    id: 31,
    price: 1
  }, {
    id: 32,
    price: 1
  }]
};

let arr = [];

let ids = [32, 31, 124]

for (let i = 0; i < Object.keys(obj.items).length; i++) {
  for (let key in obj.items) {
    arr.push(obj.items[i].id)
  }
}

let unique = new Set(arr)

let new_arr = [...unique]

let coincidences = 0;

for (let i = 0; i < ids.length; i++) {
  if (ids.includes(new_arr[i])) coincidences++
}

if (coincidences === new_arr.length) {
  alert("У пользователя в items есть все элементы из массива ids")
} else {
  alert("У пользователя в items нету всех элементов из массива ids")
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question