Dynamically update Array of objects with Mongoose - javascript

I have documents in my collection that look like this
let obj = {
email: hello#gmail.com,
deckName: hello,
data: [
{question: question1,
answer: answer1,
openHistory: ['12.06.22', '13.08.22'] //=> goal: []
},
{question: question2,
answer: answer2,
openHistory: ['14.05.22', '18.03.22'] //=> goal: []
},
]
}
I would like to filter all the documents for a specific email and set the openHistory to an empty array.
My try:
const Deck = require('../server/models/deck');
const deleteHistory = await Deck.updateMany({email:email}).data.forEach(x=>x.openHistory === [])
Thanks for reading!

Related

How to filter few properties of an object which is in Array of objects if one property equals property from another object

I have a object which has some properties for one user, and I have array of objects which is returned from API.
My goal is to check which object of Array of objects has the same property as the one single initial object, and then it should return only part of it's properities.
I have tried to use .map on Array of objects but it seems not workig.
Below is the code example. I have also prepared codesandbox if You wish.
const user =
{
name: "jan",
lastName: "kowalski",
fullName: "jan kowalski",
car: "audi"
}
;
const usersAnimal = [
{
name: "jan",
lastName: "kowalski",
fullName: "jan kowalski",
animal: "cat",
animalSize: "small",
animalName: "Bat"
},
{
name: "john",
lastName: "smith",
fullName: "john smith",
animal: "dog",
animalSize: "middle",
animalName: "Jerry"
},
{
name: "Anna",
lastName: "Nilsson",
fullName: "Anna Nilsson",
animal: "cow",
animalSize: "big",
animalName: "Dorrie"
}
];
const filtered = usersAnimal.map((userAnimal)=>userAnimal.fullName === user.fullName && return userAnimal.animalName & userAnimal.animalSize & userAnimal.animal);
thanks
https://codesandbox.io/s/admiring-edison-qxff42?file=/src/App.js
For case like this, it would be far easier if you filter it out first then proceed using map:
const filtered = usersAnimal
.filter((animal) => animal.fullName === user.fullName)
.map(({ animalName, animalSize, animal }) => {
return {
animalName,
animalSize,
animal
};
});
I am providing a for loop solution as I haven't learnt many array methods in javascript.
For me the simplest option is to use a for loop and an if check to loop through the arrays values to check for included values.
for (let v in usersAnimal) {
if (usersAnimal[v].fullName === user.fullName) {
console.log(usersAnimal[v])
}
}
The code above will log the entire usersAnimal object containing the fullname we are looking for.
{
name: 'jan',
lastName: 'kowalski',
fullName: 'jan kowalski',
animal: 'cat',
animalSize: 'small',
animalName: 'Bat'
}
commented for further understanding
for (let v in usersAnimal) {
//loops though the array
if (usersAnimal[v].fullName === user.fullName) {
//when the index value 'v' has a fullname that matches the user fullname value
// it passes the if check and logs that object value
return console.log(usersAnimal[v])
//return true...
}
//return null
}
//etc
If you want to filter, I recommend you to use filter.
The map method will create a new array, the content of which is the set of results returned by each element of the original array after the callback function is operated
const user = {name:"jan",lastName:"kowalski",fullName:"jan kowalski",car:"audi"};
const usersAnimal = [{name:"jan",lastName:"kowalski",fullName:"jan kowalski",animal:"cat",animalSize:"small",animalName:"Bat"},{name:"john",lastName:"smith",fullName:"john smith",animal:"dog",animalSize:"middle",animalName:"Jerry"}];
// Get an array of matching objects
let filtered =
usersAnimal.filter(o => o.fullName === user.fullName);
// You get the filtered array, then you can get the required properties
filtered.forEach(o => {
console.log(
'animal:%s, animalSize:%s, animalName:%s',
o?.animal, o?.animalSize, o?.animalName
);
});
// Then use map to process each element
filtered = filtered.map(o => {
const {animal, animalSize, animalName} = o;
return {animal, animalSize, animalName};
});
console.log('filtered', filtered);

Javascript, filtering array of objects and return all the unique objects

I have an array of objects, that contains properties that are objects:
let allPersons = [
{ id: "abcdefg",
name: "tom",
...
phone: {
brand: "blah"
id: "hijklm"
...
}
},
{ id: ....}, {...}, {...}
];
What I need to do is filter those objects and returning all the phones, filtering them by id so all phones returned are unique.
I tried to retrieve first all the phones:
// allPersons is the full array mentioned above
let phones = [...new Set(allPersons.map(person => person.phone))];
then I tried to return all the unique phones, but unsuccessfully:
let result = phones.map(phone => phone.id).filter((value, index, self) => self.indexOf(value) === index)
This returns only the unique ids of the phones, but I want the entire object. What can I do?
UPDATE:
phone Ids are NOT unique, e.g. nokia3310 has id 1, nokia3330 has id 2, etc: so tom and john can have the same phone and phone ids could be duplicated!
Make an object indexed by IDs instead, then take the object's values:
const phonesById = Object.fromEntries(
allPersons.map(
({ phone }) => [phone.id, phone]
)
);
const uniquePhones = Object.values(phonesById);
If you're trying to get the phone object in each object of the array, then the code below will do that for you.
It gets the phone object and stores it in a
var objArr = [
{id: "abcdefg", name: "tom", phone: {brand: "blah", id: "hijklm"}},
{id: "guidiuqwbd", name: "john", phone: {brand: "hihihih", id: "ayfva"}},
{id: "yuygeve", name: "doe", phone: {brand: "hahahah", id: "cqcqw"}}
]
var allPhoneObjects = [];
objArr.forEach(function(currObj){
var phoneObj = currObj.phone;
allPhoneObjects.push(phoneObj);
});
console.log(allPhoneObjects);
I propose you the following solution
let uniques = new Set();
const phones = allPersons.filter(({phone}) => (
uniques.has(phone.id) ? false : !!uniques.add(phone.id)
)).map(p => p.phone)
Basically, we define a Set to record ids of the phones already processed, and a filter function on the allPersons array, that returns only the phones not already in the Set. We complete with the map to extract only the portion of JSON needed
EDIT
You can use just one function on the allPersons array using the reduce function
let uniques = new Set();
const phones = allPersons.reduce( (filtered, {phone}) => {
if (!uniques.has(phone.id)) {
filtered.push(phone);
uniques.add(phone.id);
}
return filtered
}, [])

Better way to handle Arrays concatenation placed inside the Object

Well, I need to make an array concatenation, placed inside the Object.
So the worked solution I've made is:
const usersList = {
tester: [{ id: 1, //... }, //...],
custumers: [{ id: 1, //... }, //...],
admin: [{ id: 1, //... }, //...]
}
let allUsers = []
Object.keys(usersList).forEach(listKey => {
allUsers = [
...allUsers,
...usersList[listKey]
]
})
return allUsers
Besides, I wonder perhaps there is present a much fashionable way to deal with such a case? I tried this one, but it doesn't work:
[...Object.keys(usersList).map(listKey => usersList[listKey])]
Take the object's values, which will give you an array of arrays, then flatten:
const allUsers = Object.values(usersList).flat();
If you can't use .flat, then:
const allUsers = [].concat.apply(...Object.values(usersList));
Another way is to use flatMap
const usersList = {
tester: [{ id: 1 }],
custumers: [{ id: 1 }],
admin: [{ id: 1 }]
};
const res = Object.values(usersList).flatMap(x => x);
console.log(res);

How to perform array join in Node.js efficiently/fast similar to MongoDB $lookup?

I want to perform a $lookup in Node.js similar to $lookup aggreation from MongoDB.
I have a solution but I'm not sure how fast it performs with more objects in each of the two arrays or with bigger objects.
let users = [
{userId: 1, name: 'Mike'},
{userId: 2, name: 'John'}
]
let comments = [
{userId: 1, text: 'Hello'},
{userId: 1, text: 'Hi'},
{userId: 2, text: 'Hello'}
]
let commentsUsers = [
{userId: 1, text: 'Hello', user: {userId: 1, name: 'Mike'}},
{userId: 1, text: 'Hi', user: {userId: 1, name: 'Mike'}},
{userId: 2, text: 'Hello', user: {userId: 2, name: 'John'}}
] //Desired result
I know this can be done easily with ECMA6 arrays. For example:
let commentsUsers = comments.map(comment => {comment, users.find(user => user.userId === comment.userId)} )
I that an effective way to do this for a large number of users eg. 1M users. How does lodash compare to this or any other more specialized library? Are there better ways to do this with vanilla JS eg. with Array.prototype.reduce()? Can indexing be used in any way to improve the performance of the join?
Edit:
My ideal solution
let users = [{userId:1,name:'Mike'},{userId:2,name:'John'}]
let comments = [{userId:1,text:'Hello'},{userId:1,text:'Hi'},{userId:2,text:'Hello'}];
let usersMap = new Map(users.map(user => [user.userId, user]))
let commentsUsers = comments.map(comment => ({...comment, user: usersMap.get(comment.userId)}))
console.log(commentsUsers)
Thanks for the feedback!
Your desired result is not a proper data structure. You are missing a key to your object of e.g. {userId: 1, name: 'Mike'}. I added user as the key value for a indexing solution.
First I create a Map where the userId will be our loop-up value. Afterwards I just iterate over the comments with map, transforming each object to a new one that contains all the comment information plus a new k-v pair of user. For that pair we don't need to use find anymore instead we have a simple HashMap get call.
Time-complexity-wise this changes the code from O(n^2) to O(n).
let users = [{userId:1,name:'Mike'},{userId:2,name:'John'}],
comments = [{userId:1,text:'Hello'},{userId:1,text:'Hi'},{userId:2,text:'Hello'}];
function mergeCommentUser(users, comments) {
let map = new Map(users.map(v => [v.userId, v]));
return comments.map(o => ({...o, user: map.get(o.userId)}));
}
console.log(JSON.stringify(mergeCommentUser(users,comments)))
Depending on what you want (and to save on redundancy), you could also change the following line:
let map = new Map(users.map(v => [v.userId, v]));
to the following instead:
let map = new Map(users.map(v => [v.userId, v.name]));
By that your result would look like:
[
{"userId":1,"text":"Hello","user":"Mike"},
{"userId":1,"text":"Hi","user":"Mike"},
{"userId":2,"text":"Hello","user":"Paul"}
]
Otherwise, you could omit the comment.userId and instead add the full user to the object for another way to avoid redundancy.
Currently, the code example you provide is O(n * m), or, O(n2). You could create a map of each of the userId's and their respective indexes in the users array, and then rather than find the user, you can directly access it by index. This will reduce the time to O(n + m), that is, O(n).
The code would look something like this:
const users = [{ userId: 1, name: "Mike" }, { userId: 2, name: "John" }];
const comments = [
{ userId: 1, text: "Hello" },
{ userId: 1, text: "Hi" },
{ userId: 2, text: "Hello" }
];
const map = new Map(users.map((o, i) => [o.userId, i]));
console.log(
comments.map(o => {
const index = map.get(o.userId);
return index !== undefined
? {
comment: o.text,
user: users[index]
}
: o;
})
);
Obviously, you can modify the end result, but this approach would be much more efficient than the one you proposed.

Merge objects with corresponding key values from two different arrays of objects

I've got two arrays that have multiple objects
[
{
"name":"paul",
"employee_id":"8"
}
]
[
{
"years_at_school": 6,
"department":"Mathematics",
"e_id":"8"
}
]
How can I achieve the following with either ES6 or Lodash?
[
{
"name":"paul",
"employee_id":"8"
"data": {
"years_at_school": 6
"department":"Mathematics",
"e_id":"8"
}
}
]
I can merge but I'm not sure how to create a new child object and merge that in.
Code I've tried:
school_data = _.map(array1, function(obj) {
return _.merge(obj, _.find(array2, {employee_id: obj.e_id}))
})
This merges to a top level array like so (which is not what I want):
{
"name":"paul",
"employee_id":"8"
"years_at_school": 6
"department":"Mathematics",
"e_id":"8"
}
The connector between these two is "employee_id" and "e_id".
It's imperative that it's taken into account that they could be 1000 objects in each array, and that the only way to match these objects up is by "employee_id" and "e_id".
In order to match up employee_id and e_id you should iterate through the first array and create an object keyed to employee_id. Then you can iterate though the second array and add the data to the particular id in question. Here's an example with an extra item added to each array:
let arr1 = [
{
"name":"mark",
"employee_id":"6"
},
{
"name":"paul",
"employee_id":"8"
}
]
let arr2 = [
{
"years_at_school": 6,
"department":"Mathematics",
"e_id":"8"
},
{
"years_at_school": 12,
"department":"Arr",
"e_id":"6"
}
]
// empObj will be keyed to item.employee_id
let empObj = arr1.reduce((obj, item) => {
obj[item.employee_id] = item
return obj
}, {})
// now lookup up id and add data for each object in arr2
arr2.forEach(item=>
empObj[item.e_id].data = item
)
// The values of the object will be an array of your data
let merged = Object.values(empObj)
console.log(merged)
If you perform two nested O(n) loops (map+find), you'll end up with O(n^2) performance. A typical alternative is to create intermediate indexed structures so the whole thing is O(n). A functional approach with lodash:
const _ = require('lodash');
const dataByEmployeeId = _(array2).keyBy('e_id');
const result = array1.map(o => ({...o, data: dataByEmployeeId.get(o.employee_id)}));
Hope this help you:
var mainData = [{
name: "paul",
employee_id: "8"
}];
var secondaryData = [{
years_at_school: 6,
department: "Mathematics",
e_id: "8"
}];
var finalData = mainData.map(function(person, index) {
person.data = secondaryData[index];
return person;
});
Sorry, I've also fixed a missing coma in the second object and changed some other stuff.
With latest Ecmascript versions:
const mainData = [{
name: "paul",
employee_id: "8"
}];
const secondaryData = [{
years_at_school: 6,
department: "Mathematics",
e_id: "8"
}];
// Be careful with spread operator over objects.. it lacks of browser support yet! ..but works fine on latest Chrome version for example (69.0)
const finalData = mainData.map((person, index) => ({ ...person, data: secondaryData[index] }));
Your question suggests that both arrays will always have the same size. It also suggests that you want to put the contents of array2 within the field data of the elements with the same index in array1. If those assumptions are correct, then:
// Array that will receive the extra data
const teachers = [
{ name: "Paul", employee_id: 8 },
{ name: "Mariah", employee_id: 10 }
];
// Array with the additional data
const extraData = [
{ years_at_school: 6, department: "Mathematics", e_id: 8 },
{ years_at_school: 8, department: "Biology", e_id: 10 },
];
// Array.map will iterate through all indices, and gives both the
const merged = teachers.map((teacher, index) => Object.assign({ data: extraData[index] }, teacher));
However, if you want the data to be added to the employee with an "id" matching in both arrays, you need to do the following:
// Create a function to obtain the employee from an ID
const findEmployee = id => extraData.filter(entry => entry.e_id == id);
merged = teachers.map(teacher => {
const employeeData = findEmployee(teacher.employee_id);
if (employeeData.length === 0) {
// Employee not found
throw new Error("Data inconsistency");
}
if (employeeData.length > 1) {
// More than one employee found
throw new Error("Data inconsistency");
}
return Object.assign({ data: employeeData[0] }, teacher);
});
A slightly different approach just using vanilla js map with a loop to match the employee ids and add the data from the second array to the matching object from the first array. My guess is that the answer from #MarkMeyer is probably faster.
const arr1 = [{ "name": "paul", "employee_id": "8" }];
const arr2 = [{ "years_at_school": 6, "department": "Mathematics", "e_id": "8" }];
const results = arr1.map((obj1) => {
for (const obj2 of arr2) {
if (obj2.e_id === obj1.employee_id) {
obj1.data = obj2;
break;
}
}
return obj1;
});
console.log(results);

Categories