Here is an example database I have in mongodb.
[
{name: "Tommy", age: 12, _id: 12345 },
{name: "Pat", age: 22, _id: 54321 },
{name: "Bridie", age: 64, _id: 98765 }
]
How do I update the age of Pat to be 50 and the age of Tommy to be 20 in a single query using updateMany?
Im currently updating them individually in a for loop using this method.
const peopleToBeUpdated = [
{ name: "Pat", age: 50 },
{ name: "Tommy", age: 20 }
]
for (const person of peopleToBeUpdated) {
try {
await peopleSchema.updateOne({ name: person.name }, { $set: { age: person.age }})
} catch (error) {
}
}
Any help is appreciated, thanks..
Related
This question already has answers here:
Is there a way to sort/order keys in JavaScript objects?
(9 answers)
Closed last year.
I could add "id" to each object in the array "data":
const data = [
{ name: "John", age: 24 },
{ name: "Marry", age: 18 },
{ name: "Tom", age: 15 },
]
for(const key in data) {
data[key]['id'] = key;
}
console.log(data);
But "id" is added to the last in each object in the array "data":
[
{ name: "John", age: 24, id: "0" },
{ name: "Marry", age: 18, id: "1" },
{ name: "Tom", age: 15, id: "2" }
]
My desired result is this below adding "id" to the first in each object in the array "data":
[
{ id: "0", name: "John", age: 24 },
{ id: "1", name: 'Marry', age: 18 },
{ id: "2", name: 'Tom', age: 15 }
]
Are there any ways to do that?
Create the array "newData" with "id" and the array "data":
const data = [
{ name: "John", age: 24 },
{ name: "Marry", age: 18 },
{ name: "Tom", age: 15 },
]
const newData = [];
for(const key in data) {
const obj = {
id: key,
...data[key]
}
newData.push(obj);
}
console.log(newData);
This is the result:
[
{ id: "0", name: "John", age: 24 },
{ id: "1", name: 'Marry', age: 18 },
{ id: "2", name: 'Tom', age: 15 }
]
In addition, if you want "id" of Number type, use "Number()":
const data = [
{ name: "John", age: 24 },
{ name: "Marry", age: 18 },
{ name: "Tom", age: 15 },
]
const newData = [];
for(const key in data) {
const obj = {
id: Number(key), // Here
...data[key]
}
newData.push(obj);
}
console.log(newData);
This is the result:
[
{ id: 0, name: "John", age: 24 },
{ id: 1, name: 'Marry', age: 18 },
{ id: 2, name: 'Tom', age: 15 }
]
This question already has answers here:
Remove property for all objects in array
(18 answers)
Closed 1 year ago.
I have an array of objects with name and age property:
[
{ name: "Matthew", age: 23 },
{ name: "James", age: 20 },
{ name: "Daniel", age: 25 },
{ name: "Joshua", age: 22 }
]
I want to remove age property from all of the objects and print in console like
[
{ name: "Matthew" },
{ name: "James" },
{ name: "Daniel" },
{ name: "Joshua" }
]
Iterate over your array and use delete keyword.
let array = [
{ name: "Matthew", age: 23 },
{ name: "James", age: 20 },
{ name: "Daniel", age: 25 },
{ name: "Joshua", age: 22 }
]
array.forEach(function(v){ delete v.age });
console.log(array);
You can use map function to achieve this.
let output = test.map(({name}) => ({name}));
If you want to filter with multiple object you can add after name like {name, salary}
var test =[
{ name: "Matthew", age: 23 },
{ name: "James", age: 20 },
{ name: "Daniel", age: 25 },
{ name: "Joshua", age: 22 }
];
let output = test.map(({name}) => ({name}));
console.log(JSON.stringify(output, null, 2));
const newData = oldData.map(item=>({name:item.name}))
let a = [{ name: "ben", age: 25 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 }]
let case1 = { name: "ben", age: 10 }
let case2={ name: "jack", age: 30 }
case1:
i expect the result to be
[{ name: "ben", age: 10 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 }]
where "ben" is existing so it replaces age to 10
case2:
i expect the result to be
[{ name: "ben", age: 25 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 },{ name: "jack", age: 30 }]
where "jack" is not there in the array so it adds to the array
how to write a function which does this functionality
Yours is a good case for Array.prototype.findIndex (MDN), which is like Array.prototype.find but returns the found index instead of the item.
let a = [{ name: "ben", age: 25 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 }]
let case1 = { name: "ben", age: 10 }
let case2 = { name: "jack", age: 30 }
const arrayUpsert = function (array, object) {
const objectIndex = array.findIndex(item => item.name == object.name)
if (objectIndex == -1) {
array.push(object)
} else {
array[objectIndex] = { ...array[objectIndex], ...object }
}
return array
}
console.log(arrayUpsert(a, case1))
console.log(arrayUpsert(a, case2))
/* [
{ name: 'ben', age: 10 },
{ name: 'jeffrey', age: 10 },
{ name: 'daniel', age: 20 }
]
[
{ name: 'ben', age: 10 },
{ name: 'jeffrey', age: 10 },
{ name: 'daniel', age: 20 },
{ name: 'jack', age: 30 }
] */
Can be done with a for loop as well.
function untitled(original, newObj) {
for (let index = 0; index < original.length; index++) {
if (original.name && newObj.name === a[index].name) {
original[index] = {...newObj};
console.log(original); return;
}
}
original.push(newObj); console.log(original);
}
let a = [{ name: "ben", age: 25 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 }]
let case1 = { name: "ben", age: 10 }
let case2 = { name: "jack", age: 30 }
untitled(a, case1);
untitled(a, case2);
I'm using ramda library in my solution:-
Check whether the key exist in any of the object in array by
idx = R.findIndex(R.propEq('name', 'ben'), a). If idx<0 then we can directly push the object else go to the next step.
We have the index(idx), we just have to do a[idx].age="--".
I have the following data in my MongoDB, modeled via my Person model:
{ _id: 135, name: 'Alfie', age: 26 }
{ _id: 217, name: 'Ronny', age: 34 }
{ _id: 400, name: 'Sandy', age: 45 }
{ _id: 676, name: 'William', age: 24 }
{ _id: 987, name: 'Debra', age: 31 }
{ _id: 356, name: 'Kevin', age: 47 }
Now I run the following query:
const findQuery = Person.find({ _id: { $lt: 300 } }).select({ name: 1 })
findQuery.exec().then(doc => {
for (let person of doc) {
console.log(person)
console.log(person._id)
console.log(person.name)
}
}
The output is:
{ _id: 135, name: 'Alfie' }
135
undefined
{ _id: 217, name: 'Ronny' }
217
undefined
My question is, why is the string contained within person.name return undefined? where as the object itself and person._id is returned correctly.
I found the answer, name was missing from mongoose.Schema, so it couldn't find the value, even if it was present in the database.
First array
userData = [
{ name: abc, age: 24 },
{ name: ghi, age: 22 },
{ name: tyu, age: 20 }
];
Second array
userAge = [
{ age: 25 },
{ age: 26 },
{ age: 22 }
];
Both arrays have the same length.
How do I update the useData[0].age with userAge[0] using Underscore.js?
Since you need to do this over a list of dictionaries, you will need to iterate over the list using _.each.
Something like this will help,
_.each(userData, function(data, index) {
data.age = userAge[index].age;
});
While #martianwars is correct, it could be a little more generic, thus more useful, if it could apply any attribute.
Say we have an array of changes to apply, with each not being necessarily the same attribute or even multiple attributes per object:
var changes = [
{ age: 25 },
{ name: "Guy" },
{ name: "Pierre", age: 22 }
];
Changes could be applied with _.extendOwn
_.each(userData, function(data, index) {
_.extendOwn(data, changes[index]);
});
Proof of concept:
var userData = [{
name: "abc",
age: 24
}, {
name: "ghi",
age: 22
}, {
name: "tyu",
age: 20
}];
var changes = [{
age: 25
}, {
name: "Guy"
}, {
name: "Pierre",
age: 22
}];
_.each(userData, function(data, index) {
_.extendOwn(data, changes[index]);
});
console.log(userData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
This will only work if the arrays are in sync. Meaning that if there are 4 objects in the userData array, and only 3 changes, they need to be at the right index and that could become a problem.
A solution to this is to have an identification property, often represented by an id attribute.
userData = [
{ id: '1', name: 'abc', age: 24 },
{ id: '2', name: 'ghi', age: 22 },
{ id: '3', name: 'tyu', age: 20 }
];
See Merge 2 objects based on 1 field using Underscore.js for details.