My current logic is the following creating adding a document with a user id in to users collection, and push the first object, then on the second call I want to be able to update the excising array with a new object.
const docRef = doc(db, 'user', _authContext.currentUser.uid);
const payload = { items: [{item1 : 1}] };
await setDoc(docRef, payload);
// New array after update (second call of the function)
items: [{item1 : 1}, {item2 : 2}]
I think you're looking for:
await updateDoc(docRef, { items: arrayUnion({ item2: 2 }) });
Also see the Firebase documentation on adding items to an array.
Related
So I am receiving an array of Objects, each one has a "attributes.seller" property. Then I am using a forEach( ) to go over each one and create a new object with only the properties I need and pushing them to a new array, including the Seller property.
The issue is that on ALL the received objects the "Seller" property exists and its a string.
However, after constructing the new object most of the seller properties show as "seller: {$$typeof: Symbol(react.element), type: 'button', key: null, ref: null, props: {…}, …}"
BUT not all of them, some do show correctly. So IDK whatI am doing wrong if my code was working before and it still works but not for all the items.
This is the object array i am receiving
This is where I itirate over each object:
createdResults.forEach((item) => {
console.log(item.attributes.seller);
const offer = {
itemId: Number(item.attributes.itemId),
token: item.attributes.token,
amount: item.attributes.amount,
price: item.attributes.price,
seller: item.attributes.seller,
};
createdArr.push(offer);
Even when I log out to the console items.attributes.itemId, it shows EVERY SINGLE property just fine.
The issue is after I have pushed each new object into the new array that the "seller" property of it shows like this:
New Object
const getEvents = async () => {
let createdArr = [];
const created = new Moralis.Query("SaleCreateddd");
const createdResults = await created.find();
createdResults.map((item) => {
// Until here, the seller string shows up correctly for each item
console.log(item.attributes.seller);
const offer = {
itemId: Number(item.attributes.itemId),
token: item.attributes.token,
amount: item.attributes.amount,
price: item.attributes.price,
seller: item.attributes.seller,
};
// Its after the forEach loop that the seller property gets distorted
createdArr.push(offer);
itemId is already an integer remove Number()
then you are forgetting .seller
createdResults.forEach((item) => {
console.log(item.attributes.seller);
const offer = {
itemId: item.attributes.seller.Number(itemId),
token: item.attributes.seller.token,
amount: item.attributes.seller.amount,
price: item.attributes.seller.price,
seller: item.attributes.seller.seller,
};
createdArr.push(offer);```
I am trying to add to an object in firestore, the problem is the new object overwrites the previous objects so in my case only one object remains, i put a picture of the db and also the logic that I am using.
const docRef = doc(db, 'items', _authContext.currentUser.uid);
await updateDoc(docRef, {
itemlist: {
[diffrent key each time]: arrayUnion({ name: 'item whatever')}],
},
}), { merge: true };
};
You should use dot notation when updating a nested field. Also updateDoc() doesn't take the options with merge property (it's setDoc() that does). Try refactoring the code as shown below:
const docRef = doc(db, 'items', _authContext.currentUser.uid);
const differentKey = "someKey";
await updateDoc(docRef, {
[`itemList.${differentKey}`]: arrayUnion({ name: "item whatever" }),
});
I'm creating subdocuments in my event model under guests that look like below. I would like to console.log the corresponding subdoc Id as each guest id is created.
{
"guests" : [
{ "phone" : 11111,
"_id" : ObjectId("61ef629981f154bead6b0de4")
},
{ "phone" : 4444444444,
"_id" : ObjectId("61fca19f95b626e017732139")
}
]
}
I followed the mongoose docs but the code from the docs (below) only logs the first id even as each subsequent doc is created because of the index 0.
// create a comment
parent.children.push({ name: 'Liesl' });
const subdoc = parent.children[0];
console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }
subdoc.isNew; // true
I tried removing the index 0 and the console log just produces the ever-growing guests array.
module.exports.addGuest = async (req, res) => {
const event = await Event.findById(req.params.id);
const phone = req.body.guest;
event.guests.push(phone);
const guestId = event.guests[0];
console.log(guestId);
await event.save();
res.redirect(`/events/${event._id}`);
}
How do I adjust my function to log the corresponding subdoc Id as it's created?
try applying mongoose hooks on your subschema.
mongoose pre save hook is triggered every time a document is saved in your collection and you can log the id of your document which is being saved.
I have a shopping cart, when a "Add to Cart" button is pressed, It sets the object to the localStorage.
const addToCartCookie = () => {
let cartData = {
id: product._id,
name: product.name,
slug: product.slug,
productPictures: product.productPictures[0].img,
description: "sabdsjbfjsd",
price: product.storePrice,
quantity: itemCount,
};
window.localStorage.setItem("cart", JSON.stringify(cartData));
};
If again "Add to cart" button is pressed, it replaces the previous object. I need to append each object if the product._id does not exists on the "add to cart" button call.
If product._id exists (if already product exists), I need to change the quantity(old one's quantity + new one's quantity)
First you need your localStorage item as an array, then check for it's existence first, create if not exists, push after parsing the array, then stringify again to save changes.
const itemToAdd = {
id: product._id,
name: product.name,
slug: product.slug,
productPictures: product.productPictures[0].img,
description: "sabdsjbfjsd",
price: product.storePrice,
quantity: itemCount,
};
const addToCartCookie = (cartItem) => {
const cart = window.localStorage.getItem('cart');
if(cart === null) {
window.localStorage.setItem('cart', JSON.stringify([cartItem]));
} else {
const getCurrentCart = window.localStorage.getItem('cart');
const currentCart = JSON.parse(getCurrentCart);
currentCart.push(cartItem);
window.localStorage.setItem('cart', JSON.stringify(currentCart));
}
};
use like this
addToCartCookie(itemToAdd)
Try using this approach.
Make an item_array array.
Every time you add an item to your cart, first push it in the item_array and then set the complete item_array into the localStorage.
Before adding more items to the cart, get the item_array from the localStorage and push the new item into the item_array. Then again push this item_array with new item into the localStorage.
I hope you get the gist, what we're trying to do here.
That is the workflow to put a new product to you localStorage array.
let current = [
{p: "abc", q: 2},
{p: "def", q: 1},
]
let str = JSON.stringify(current);
console.log('store this string in localStorage', str)
console.log("read the string from localstorage");
let arr = JSON.parse(str)
console.log(arr)
let newProduct = {p: "hij", q: 3}
arr.push(newProduct)
console.log(arr)
how can i get all the customers with the same id in each Object into One array (unless you have a better idea)
so i can get the start and end time to show in a table for that specific customer.
the idea here is to show a table with fixed columns, and each row would be filled with customer name and start time for each of these columns instead of having multiple rows.
im looping over my API data in which it's returning multiple Objects with each having its own values for Example:
Better to use Object, where the key is the actual ID identifier: {ID1: [], ID2: []}- that way by just targeting the ID you get back all the data for that customer ID:
const response = [
{customerId:"11", customerName:"John", serviceName: "foo"},
{customerId:"88", customerName:"Anne", serviceName: "bar"},
{customerId:"11", customerName:"John", serviceName: "baz"},
];
const customers = response.reduce((dict, data) => {
if (!dict[data.customerId]) dict[data.customerId] = [];
dict[data.customerId].push(data);
return dict;
}, {});
// Get specific customer data (customerId "11"):
console.log(customers["11"]);
// Get all customers data:
console.log(customers);
This can also be done using the Map Object and its has, get and set methods:
const response = [
{customerId:"11", customerName:"John", serviceName: "foo"},
{customerId:"88", customerName:"Anne", serviceName: "bar"},
{customerId:"11", customerName:"John", serviceName: "baz"},
];
const customers = response.reduce((m, {customerId:id, ...r}) => {
if (!m.has(id)) m.set(id, []);
return (m.get(id).push(r), m);
}, new Map());
// Get specific customer data (customerId "11"):
console.log(customers.get("11"));
// Get all customers data:
console.log([...customers]);