I have an event I'm storing in my database. It is stored as
events
my_party123
info
-KZbdiR_PBrAwxYvUR4U
name: 'John'
city: 'Los Angeles'
my_party124
...
However, I'm trying to retrieve this info and I can't quite get it.
I tried
ref
.child('events')
.child('my_party123') // I also tried .push('my_party123')
.once('value')
.then(snapshot => {
console.log(snapshot.key) // my_party123
console.log(snapshot.val().info)
// this shows object with
// "-KZbdiR_PBrAwxYvUR4U" property, this is the pushed key property
im trying to access
})
.pushed is creating new keys when i called it - how do i just access the value stored in my database?
If you're looking to have unique event URLs that point at events, I'd recommend a change to your data structure to be something more like:
events
-KZ123PUSHID
name: 'John'
location: 'Los Angeles'
-KZ124PUSHID
name: 'Morgan'
location: 'New York City'
eventNames
my_party_123: '-KZ123PUSHID'
sweet_nyc_part: '-KZ124PUSHID'
Then, in your code, you could do something like:
var eventNamesRef = firebase.database().ref('eventNames');
var eventsRef = firebase.database().ref('events');
var event;
eventNamesRef.child(nameFromUrl).once('value').then(nameSnap => {
eventsRef.child(nameSnap.val()).on('value', eventSnap => {
event = eventSnap.val();
});
});
Related
I have an application with a form that collects data from users. I want to store this data in MongoDB. However at the moment only the Id is being shown in the database.
I am sending the data in the following format:
let userData = [{
Name: customerName,
address: address,
workType: work,
time: date,
imageOne: image1,
imageTwo: image2,
imageThree: image3,
}];
/* submitting the data */
const scheduleEvent = (e) => {
e.preventDefault();
axios.post(
"My url",
userData
)
};
/* end of submission*/
I have read a few questions here on Stack Overflow that the issue is the object in application and MongoDB are different. Here is my webhook code
exports = async function(payload, response) {
if (payload.body) {
const body = EJSON.parse(payload.body.text());
const customerEvents= context.services.get("mongodb-atlas").db("Curb").collection("Customer-event");
const event = {
Name: body.Name,
address: body.address,
workType: body.workType,
time: body.time,
imageOne: body.image1,
imageTwo: body.image2,
imageThree: body.image3,
};
return await customerEvents.insertOne(event);
}
return {}
I have done some tinkering with the names to see if anything will be sent, but so far nothing. I figured that if the issue were the names of the properties that at least one would go through, like the Name property.
My full page is viewable here.
If you say only the Id is created on MongoDB, maybe there is a problem with the way the data is dealt with.
One possible cause is that userData is of type array. And you're never accessing it. Maybe try:
axios.post(
"My url",
userData[0]
)
Or just keep it as an object:
let userData = {
Name: customerName,
address: address,
workType: work,
time: date,
imageOne: image1,
imageTwo: image2,
imageThree: image3,
};
Another suggestion is to try payload.body.text (instead of .text()). Or to check if it has other properties, like .json or .data.
Well, this is my response. results is a new empty array. address is my nested object in user
response.data.forEach(user => {
results.push({
id: user.id,
name: user.name,
address: user.address.number
})
})
This way I get undefined result from address object. So how can I access it correctly?
It's hard to answer without seeing some sample data but from the look of it, I would guess user.address.number is simply not defined in your data set. Why would you expect it is?
By the way, your combination of forEach and push could be simplified with map:
var results = response.data.map(user => ({
id: user.id,
name: user.name,
address: user.address.number
}));
So I have a model created/loaded normally:
let contact = self.get('store').createRecord('contact');
I then get the address, which is a BelongsTo relation on the model:
let address = contact.get('address');
the returned address variable is a Proxy object, which the promise resolves as either the related model or null.
The question is how can I create a new address model and assign it to the original contact object, but with only the address proxy object?
If you want to create a new address record (and not model) and assigning it to your newly created contact, you can do the following:
const store = this.get('store');
const contact = store.createRecord(
'contact',
{
name: 'Jack',
address: store.createRecord('address')
}
);
or if you already have an address proxy and you want to create a new one only if it results to null:
const store = this.get('store');
const contact = store.createRecord('contact', { name: 'Jack' });
my_address_proxy.then(address => {
contact.set('address', address || store.createRecord('address'));
});
I have given an array of document id's which I want to add to Firestore.
let documentIds = [
'San Francisco',
'New York',
'Las Vegas'
]
Each document should have a predefined set of properties.
let data = {
country: 'US',
language: 'English'
}
Is there some function inside the Firebase Admin SDK that can create all documents at once, without iterating through the array of documentIds?
This should help. Sam's answer will give you a good understanding of how to use batch writes. Be sure to check out the documentation that he linked to.
I don't want to upset Sam. He fixed my laptop, yesterday :-)
Setting a batch with an array
let documentIds = [
'San Francisco',
'New York',
'Las Vegas'
]
let data = {country: 'US', language: 'English'}
var batch = db.batch();
documentIds.forEach(docId => {
batch.set(db.doc(`cities/${docId}`), data);
})
batch.commit().then(response => {
console.log('Success');
}).catch(err => {
console.error(err);
})
You can do a batched write. You'll still need to iterate through the docs to add them all to the batch object, but it will be a single network call:
Example:
// Get a new write batch
var batch = db.batch();
// Set the value of 'NYC'
var nycRef = db.collection("cities").doc("NYC");
batch.set(nycRef, {name: "New York City"});
// Update the population of 'SF'
var sfRef = db.collection("cities").doc("SF");
batch.update(sfRef, {"population": 1000000});
// Delete the city 'LA'
var laRef = db.collection("cities").doc("LA");
batch.delete(laRef);
// Commit the batch
batch.commit().then(function () {
// ...
});
https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes
Suppose we have a form that can contain an array of values.
For this case Angular provides us with FormArray class.
this.form = new FormGroup({
addresses: new FormArray([]),
})
Also we have an ability to use NgForm#setValue. This can be used i.e. to populate the form with some data retrieved from server.
When I receive new data from the server, I want to populate the form with that data. For example, my data looks like this:
const data = {
addresses: [
{ country: 'USA', city: 'New York' },
{ country: 'Germany', city: 'Berlin' },
]
}
Now it's time to populate the form with this data.
When I try to simply invoke this.form.setValue(data) I get an error:
Cannot set property stack of [object Object] which has only a getter
How do I populate the form with data, but with these requirements:
I know the shape of addresses property.
I don't know the quantity of addresses in that data.addresses array.
Try like this below
this.form.setControl('addresses', this.formBuilder.array(this.data.addresses || []));