Meteor update multiple nested array elements - javascript

let items = [
{
name: "Choco",
id: "12344",
qty: 24,
status: "open"
},
{
name: "Mils",
id: "12346",
qty: 5,
status: "open"
},
{
name: "boom",
id: "12345",
qty: 10,
status: "open"
}
];
Given the array above, is it possible to update the document without calling a forEach on each of them.
For instance what i am currently doing is this
_.each(items, function( item ) {
Orders.update({_id: doc.orderId, "items.id": item.id},
{
"$set": {
'items.$.status': item.status,
'items.$.qty': item.qty,
}
})
})
is it possible to just update the entire array at once without create a new mongo db transaction

You can read all the order:
var order = Orders.findOne({_id: doc.orderId});
Than adjust order.items with the new data and then update in a single operation:
Orders.update({_id: doc.orderId },{"$set": {items:order.items}});

Related

Check the array of element in another array of set of elements in javascript

Let openstatus = ["Open","Created","Checked"]
Let obj = [
{ id: 00023434, Authore: tester, status: Approval },
{ id: 0002578, Authore: apitester, status: Open },
{ id: 0002847, Authore: usertester, status: Created },
{ id: 0002847, Authore: usertester, status: Draft },
]
Example :
Let status = "Draft"
obj.filter((e1)
return e1.status.includes(status)
);
from above one output will be below output:[id: 0002847, Authore: usertester, status: Draft]
When the status has all list of values ["Open","Created","Checked"] then how to filter it
I need to check the above openstatus of list of array status values match to check from obj array and to find to give last 2 records. can I know simple step to resolve this issue.As I am new to javascript
You can just filter using the condition that the openstatus array includes the element's status.
let openstatus = ['Open', 'Created', 'Checked'];
let obj = [
{ id: 00023434, Authore: 'tester', status: 'Approval' },
{ id: 0002578, Authore: 'apitester', status: 'Open' },
{ id: 0002847, Authore: 'usertester', status: 'Created' },
{ id: 0002847, Authore: 'usertester', status: 'Draft' },
];
console.log(obj.filter(el => openstatus.includes(el.status)));
Check out filter() method. Give the documentation a read.

Map array of objects by ID and update each existing object in the array

I'm trying to make a call, return an array of objects, then loop through each object in the array by the id and make an additional call. With this second fetch, I need to add a new object to each corresponding object within the original array. Please see code samples below and thank you in advance!
Steps:
Pass search params into postSearchPromise
Map over results and store an array of all id's
Pass each id into the getMediaPromise (I've already defined the token)
Add each response object from the getMediaPromise to the corresponding object in the existing array.
Use a reducer to store the final results (This is a React Native app, i'm using a FlatList on the following screen that points to this stored data, looping through the array and displaying the list on screen)
async function search() {
const toSend = {
title,
age,
location
};
try {
const results = await postSearchPromise(token, toSend);
const theUsers = await results.map(getUsers);
function getUsers(item) {
var users = item.id;
return users;
}
const avatars = await getMediaPromise(token, theUsers);
const mapped = await results.map(element => ({avatar: avatars ,...element}));
dispatch({type: 'SEARCH_RESULTS', payload: mapped});
} catch (e) {
console.log("The Error:" , e);
}
}
Currently, this almost works, but "avatar" takes all of the id's from getUsers and sends them in a comma separated list, together at once, inside the "getMediaPromise," - this is not the intent, but I understand why the code is behaving this way. I'm not sure how to loop through each id and add the new object to each existing object in the array.
The search results I start with:
[
{
id: "123",
name: "John",
location: "USA"
},
{
id: "456",
name: "Jane",
location: "USA"
},
{
id: "789",
name: "Jerry",
location: "USA"
}
]
The search results I need to finish with:
[
{
id: "123",
name: "John",
location: "USA",
avatar: {
type: "default",
status: "200",
ok: true,
url: "http://localhost:3000/media/123"
}
},
{
id: "456",
name: "Jane",
location: "USA",
avatar: {
type: "default",
status: "200",
ok: true,
url: "http://localhost:3000/media/456"
}
},
{
id: "789",
name: "Jerry",
location: "USA",
avatar: {
type: "default",
status: "200",
ok: true,
url: "http://localhost:3000/media/789"
}
}
]
I'm open to an entirely different way to do this, but as mentioned above... I'm using a FlatList on the following screen so it's essential that this is a single array of objects so my FlatList can easily loop over the stored data and pull each piece accordingly. Thanks!

mongodb add item in array

await Cart.update(
{ $elemMatch: { user_id: decoded._id } },
{
$addToSet: {
"cart.&.items": {
product_id: req.query.product_id,
quantity: 1,
},
},
}
);
My goal is to add elements to the array of items in the cart.
There's no syntax with & sign. MongoDB offers $ as a positional operator which allows you to modify existing item but you don't needed since you just want to append a new object to an array, try:
{
$addToSet: {
"cart.items": {
product_id: req.query.product_id,
quantity: 1,
}
}
}
Cart.updateMany(
{ user_id: decoded._id },
{
$push: {
"cart.items": {
product_id: req.query.product_id,
quantity: 1,
},
},
}
)
I finally found the right method through trial and error.

Remove object fields by updating the complete object

This is some data which is stored in a mongoDB document:
{
_id: "123"
order: 1
parent: "Dueqmd64nTxM3u9Cm"
type: "article"
unit: "kg"
}
While all the saved data will be calculated and validated first (that's why I don't use only data = { order: 2 }), I'm using the complete object to update the document:
var data = {
order: 2
parent: "Dueqmd64nTxM3u9Cm"
type: "article"
unit: "kg"
}
Collection.update(
{ _id: 123 },
{ $set: data }
);
This is working.
But if I want to remove some values, it doesn't work:
var data = {
order: 2
parent: "Dueqmd64nTxM3u9Cm"
type: "article"
unit: undefined
}
Collection.update(
{ _id: 123 },
{ $set: data }
);
I'm expecting the unit-field to get removed. But that isn't the case...
To remove fields, use the $unset operator:
data = {
unit: ""
};
Collection.update(
{ _id: 123 },
{ $set: data }
);

AJAX Request Returns Doubled List of Objects - YUI

I am using YUI's Datatable Column Formatter to format some data returned from an AJAX request. Here's the config:
var dataTable = new Y.DataTable(
{
id: 'my-table',
height: '500px',
width: '500px'
});
var columns = [{
key: 'id',
label: 'ID'
}, {
label: 'Name',
formatter: function (o) {
console.log(o.data);
return o.data.name;
}
},
{
key: 'department',
label: 'Department'
}
];
function search(){
dataSource = new Y.DataSource.IO({source: '/search' });
dataSource.sendRequest({
dataType: 'json',
on: {
success: function(e) {
response = e.data.responseText;
data = Y.JSON.parse(response);
dataTable.set('columns', columns);
dataTable.set('data', data.content);
},
failure: function(e) {
//do stuff
}
});
}
My table gets populated fine
And this is returned from the console
Object {id: 1, name: "Bob", department: 001}
Object {id: 2, name: "Andy", department: 003}
However if I launch the request a second time, the number of Objects returned doubles
Object {id: 1, name: "Bob", department: 001}
Object {id: 2, name: "Andy", department: 003}
Object {id: 1, name: "Bob", department: 001}
Object {id: 2, name: "Andy", department: 003}
While the data still displays, this duplication breaks functionality elsewhere. Additionally, no matter the number of times the request is launched, only the doubled list returns. Any idea why the Objects are getting combined?
Try removing the existing data on each AJAX request. $('#myTableID').remove() and then recreate. It seems your AJAX call is appending to the existing content

Categories