How to foreach data and update data in loop using adonisjs I wannt to do something like this
in php I do this
$emp = Employee::all()
foreach($emp as $data) {
$emp_store = Store::where('emp_id', $emp->id);
$emp_store->name = $emp_name;
$emp->save()
}
but after I change into adonisjs How can I do something like this in Controller . Now I try to do
const emp = await Employee.all();
for(var val of emp) {
// I want to update data using each emp id
console.log(val)
}
after I try to do I got an error said emp is not iterable
I just find it
for(let i in emp.rows) {
const lobby = emp.rows[i]
console.log(lobby) // you should be able to have access to name now
}
thnks
To convert a serializable instance to a plain array/object, call its toJSON method:
const json = emp.toJSON()
With this you can loop through the array
Related
I have an object with keys id,name like below. Based on the id i have to get customer name and update the object.
Const arr=[{id:1,name:''},{id:2,name:''}];
_.forEach (arr, function (obj)){
const result=getcustomer(obj.id, function (data){
//Getting customer data here.
});
}
How can i update obj.name for each object when i get data asynchronously?
Would you not just get the index of the item you are currently on and update that array element? Or am I missing something here.
arr.forEach((item, index) => {
const result = await getCustomer(item.id);
arr[index].name = result.data.name; //however you get the data
});
Recently I was trying to append a lot of HTML form values to MongoDB database through an async process
this const createproperty are my MongoDB fields which i have taken in an array
const createProperty = ['propertyType',
'propertyName',
'bhkType',
'ownershipType',
'builtUpArea',
'propertyAge',
'floorType',
'floorNumber',
'numberOfFloors',
'city',
'expectedPrice',
]
.. these ids are some id's from the HTML form which i have put in an array
const myids = ['#thisPropertyType',
'#thisPropertyName',
'#thisBhk',
'#thisOwnerShip',
"#thisArea",
'#thisAge',
'#thisFloor',
'#thisFloorNo',
'#thisTotalFloor',
'#thisCity',
'#thisEp', ]
this newproperty will give me the values from the Html form, all of the values are stored in the form of an array and this for loop works just fine which gives me all the form values perfectly
const newProperty = new Array();
for(var i=0;i<myids.length;i++){
newProperty[i] = $(myids[i]).val();
}
const form = new FormData();
for(var i=0;i<newProperty.length;i++){
form.append(createProperty[i],newProperty[i]);
}
await createData(form);
this is the function which follows the async process
export const createData = async (data) => {
try{
for (var value of data.values()) {
console.log(value);
}
const res = await axios({
method: 'POST',
url: '/api/v1/myapi',
data
});
if(res.data.status==='success'){
alert('success');
}
console.log(data);
}
catch(err){
alert('error');
}
}
i console.logged the values from the createdata function, it gives me the values perfectly but it is not pushing the values to the mongodb server, when i look at the collection, there is an document which is created but it has no data in it..
please help me where have i done wrong, i'm not getting where did i go wrong..
Thank you so much for helping me out!!
axios expect the data to be JSON object not FormData
This will construct the body as JSON with keys from createProperty array
const data = {};
myids.forEach((id, index) => {
data[createProperty[index]] = $(myids[i]).val();
})
then you can send these values directly through axios
await createData(data)
How to loop data in RowDataPacket.
This problem happen because in addonis QueryBuild not return same value
as lucid models
If I use lucid models every work fine
const emp = await EMP.all();
for(let i in emp.rows) {
const data = emp.rows[i]
}
After I using querybuilder I do something like this
const emp = await Database
.table('emp');
for(let i in emp.RowDataPacket) {
console.log('s')
const data = emp.RowDataPacket[i]
const emp = await emp_sell.query()
.where('emp_id',data.id);
}
It's not even display 's'
When making this query await Database.table('emp');, you ended with an RowDataPacket objects, which is an object not iterable, as a workaround you could parse it to an array as:
JSON.parse(JSON.stringify(emp))
Further reading here.
I am using angualr 4.
i have an array.
Here is my array;
this.bookings = [
{
'id':'dsjdsfhkdsjhfjkds01'
},
{
'id':'dsjdsfhkdsjhfjkds01'
}
]
I need retrieve data from database based on id.
Here is my script.
let scope = this;
scope.bookings.forEach(function(BookingItem){
var bId = BookingItem.id;
console.log("BId",bId);
scope.Bservice.getbooking(scope.at,bId).subscribe(booking => {
var responseVal = booking;
})
})
I need like forEach Take on firstvalue then get retrive data from database.After going to second value of booking then get data from database.
But i consoled value of bId.
ForEach taken on id values one by one After retreive data from database.
How can i fix this pblm.
Kindly advice me,
Thanks.
I am not understading you code at full but you have to do like this
You have to loop throught bookings array and than in argument of foreach you need vriable name not name of you class ,
Another thing is if you go in loop, you last returned value from ajax request will override vlaue of your variable , so better to store response in array thats why below code use array to store you response for each id.
let responseFromServer = new Array<any>();
this.bookings.forEach((bookingItem) => {
var bId=bookingItem.id;
console.log("BId",bId);
scope.Bservice.getbooking(scope.at,bId).subscribe(booking=>{
let response = new ResponseFromServer();
responseFromServer.Add(booking);
});
});
Since the api call response takes some time, you should wait for the response untill it is recieved.
You can use Observable forkJoin which works like a promise and processes all requests in loop and returns response.
import {Observable} from 'rxjs/Rx';
let observables = new Array();
this.bookings.forEach(function(booking){
observables.push(this.Bservice.getbooking(this.at,booking.id));
})
Observable.forkJoin(observables).subscribe(
res => console.log(res),
error => console.log('Error: ', error)
);
Here is a documentation for forkJoin
Currently my views on couchdb always return something like this:
{
"key":"somekey",
"value":"somevalue"
}
I wonder if there's any way to return something like this:
{
"somekey":"somevalue"
}
i need to access "somekey" directly without having to search the whole array for a key with "somekey" value on it.
Thanks
When using a view, there is no direct way provided by CouchDB to return the collection of documents as anything but key/value as you've seen.
You'd need to map the data on the client side into a keyed index, or request the document by the key directly from the view:
/sample/_design/docs/_view/by_somekey?key="somekey"
If you're looking for a fast map option in JavaScript (avoiding calling a function for each iteration), you could just use this simple logic of course:
// docs are the documents returned from the view
var map={};
for(var i=0,len=docs.length;i<len;i++) {
map[docs[i].key] = docs[i].value;
}
You can do this with underscoreJS (http://underscorejs.org/#reduce).
var map = {
"key":"somekey",
"value":"somevalue"
};
var result = _.reduce(map, function(key, value){
var result = {};
result[key] = value
return result;
});
alert(result.somekey);
http://jsfiddle.net/BcYtw/1/
If you do not like the format or data for Couch queries, you can reformat it at your will with list function. Something like this should work for you:
function(head, req){
send('[');
row = getRow();
if (row){
// here you make your own JS structure to be returned,
// serialize it with toJSON() and send to client with send()
// First row:
var new_row = {};
new_row[row.key] = row.value;
send(toJSON(new_row));
while(row = getRow()){
// Next rows:
send(',');
var new_row = {};
new_row[row.key] = row.value;
send(toJSON(new_row));
}
}
return ']';
}