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.
Related
is there any other way to insert a data into mongoose without using array desctructuring
i have some code below, it doesnt work, also it doesnt insert correctly into database
const data = req.file.originalname.split('.')[0].split('_');
if (data.length < 5) throw new Error('Invalid file name');
const content = await fs.readFile(req.file.path, 'utf8');
await orders.create({ data, content });
i can make this work by using this code by using array desctructuring like below, what i want to know is there any way without using desctructuring, and just using variable data like my code above
const data = req.file.originalname.split('.')[0].split('_');
if (data.length < 5) throw new Error('Invalid file name');
// const [no_telp, type, timespan, name, unique_code] = data;
const content = await fs.readFile(req.file.path, 'utf8');
await orders.create({ no_telp, type, timespan, name, unique code, content });
What you are doing is not array destructuring. Array destructuring means pulling data out of array. An example array destructuring could be const listCopy = [...list] or const listAdded = [...list, 12, 48]. If you mean this part create({ no_telp, type, timespan, name, unique code, content }); you are providing neessary data into create method. You can create an abject beforehand and just send pass it to create method. const userData = { no_telp, type, timespan, name, unique code, content }; await orders.create(userData);
Additionally, what you are trying to save is a stringified data. After reading a file with fs.readFile() you must parse it to manipulate and save in database correctly. Try this:
const stringData = await fs.readFile(req.file.path, 'utf8');
const content = JSON.parse(stringData)
console.log(content) // see the data
const userData = {no_telp, type, timespan, name, unique code, content};
await orders.create(userData);
Somehow I'm unable to update properties of a mongoose object I fetch from a MongoDB. I'm trying to follow this pattern: Mongoose Docs: Document
This is my code:
// note: getInstances just returns model.find()
let instances: InstanceDocument[] = await this.instanceService.getInstances();
instances.forEach(async (instance, index) => {
console.log(instance);
let deviceCount = await this.instanceService.getDeviceCount(instance._id);
let elementCount = await this.instanceService.getElementCount(instance._id)
instance.deviceCount = deviceCount;
instance.elementCount = elementCount;
await instance.save();
console.log(deviceCount, elementCount, instance);
})
The console.log prints the correct values for deviceCount and elementCount, but the instance object remains unmodified. It still has the unupdated values it has in the database.
Note: this is not a duplicate entry of Unable to add properties to js object, as I'm not trying to create a new object and give it properties.
Two things :
You can't use await inside an array method like forEach or map. It doesn't work (doesn't await). Use a for loop instead.
Mongoose has this weird requirement that you must explicitely tell it that a nested key has been modified in order to save it. See this question
let instances: InstanceDocument[] = await this.instanceService.getInstances();
for(let instance of instances) {
console.log(instance);
instance.deviceCount = await this.instanceService.getDeviceCount(instance._id);
instance.elementCount = await this.instanceService.getElementCount(instance._id);
instance.markModified("deviceCount"); // this
instance.markModified("elementCount"); // and this
await instance.save();
console.log(deviceCount, elementCount, instance);
}
The code above works. I made a mistake in defining the objects schema. I missed #Prop() decorator for the properties I added. This code works:
let instances: InstanceDocument[] = await this.instanceService.getInstances();
let fetchingDone = new Subject();
fetchingDone.subscribe(instances => res.json(instances))
instances.forEach(async (instance, index) => {
instance.deviceCount = await this.instanceService.getDeviceCount(instance._id);
instance.elementCount = await this.instanceService.getElementCount(instance._id);
await instance.save();
if (index+1 === instances.length) fetchingDone.next(instances);
})
I am pre-fetching a product from a database using mongoose with next.js and react-query. I was wondering why I need to do a deep copy of a nested object in order to add a key:value to it. Otherwise it does not work. Let me know what I am not understanding.
await queryClient.prefetchQuery(['productSlug', slug], async () => {
const product = await read(slug);
const existingRatingObject = product.ratings.find(
(item) => item.postedBy.toString() === user._id.toString()
);
const copyProduct = JSON.parse(JSON.stringify(product));
if (existingRatingObject) {
copyProduct.star = existingRatingObject.star;
} else {
copyProduct.star = 0;
}
console.log({ copyProduct });
return JSON.stringify(copyProduct);
});
The reason is that the product fetched is a Mongoose document not a plain old JavaScript object.
When you convert it to plain old javascript Object, you will be able to add any key to it.
You can add .lean() to you query or add toObject/toJSON to you the fetched document
i am making an asynchronous request to a database and then running a loop on the resultant data but i am getting only the last value while sending a response to front-end
routes.post('/data/qualitative/bivariate', async (req, res)=>{
const { colName1, colName2} = req.body;
var colNameObj1={};
var colNameArray1={};
colNameObj1[colName1]=1;
colNameObj1[colName2]=1;
colNameObj1['_id']=0;
//requesting data from database
const data= await dataModel.find({}, colNameObj1);
//filtering the data
const newData= data.map( (item)=>{
colNameArray1['x']= item[colName1];
colNameArray1['y']= item[colName2];
return colNameArray1
})
//in response i am getting just the data from the last index
res.json(newData)
})
In response i am getting just the data from the last index. Please advise how i can handle this asynchronous request
You must declare colNameArray1 inside the map function:
routes.post('/data/qualitative/bivariate', async (req, res)=>{
const { colName1, colName2} = req.body;
var colNameObj1={};
colNameObj1[colName1]=1;
colNameObj1[colName2]=1;
colNameObj1['_id']=0;
//requesting data from database
const data= await dataModel.find({}, colNameObj1);
//filtering the data
const newData= data.map( (item)=>{
var colNameArray1={};
colNameArray1['x']= item[colName1];
colNameArray1['y']= item[colName2];
return colNameArray1
})
//in response i am getting just the data from the last index
res.json(newData)
})
If you want all the rows, then you should push each object you can create in to an array. In the above code, you are overwriting over the same object.
Try updating the code to the following:
routes.post('/data/qualitative/bivariate', async (req, res)=>{
const { colName1, colName2} = req.body;
var colNameObj1={};
var colNameArray1={};
const dataList = [] // Create a empty array
colNameObj1[colName1]=1;
colNameObj1[colName2]=1;
colNameObj1['_id']=0;
//requesting data from database
const data= await dataModel.find({}, colNameObj1);
//filtering the data
data.forEach( (item)=>{
colNameArray1['x']= item[colName1];
colNameArray1['y']= item[colName2];
dataList.push(colNameArray1) // Push to the array
})
//in response i am getting just the data from the last index
res.json(dataList)
})
i found the issue and it has nothing to do with the asynchronous request and as mentioned above its confirmed that i am overwriting the object. Cloning the object using spread {... obj} has solved the issue. Thanks for help.
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