array destructuring mongoose create - javascript

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);

Related

Deep copy of the Object to add a key : value

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

Async Storage retrieve value of key in item

I'm new to Javascript and react native, and the question itself will be probably very easy to answer.
I'm setting up a AsyncStorage and creating a Item inside the storage, which is a .JSON that has 3 key values to it.
const saveDataToStorage = (token, userId, expirationDate) => {
AsyncStorage.setItem('userData', JSON.stringify({
token: token,
userId: userId,
expiryDate: expirationDate.toISOString()
}))
};
What I want to do now is to retrieve the "userId" value from this item in an other part of the project but here is the problem.
var PersonalId = await AsyncStorage.getItem('userData');
console.log(PersonalId);
console.log(typeof PersonalId);
I know how to access the item itself, but I have no clue how to access the special key inside it. I can not use the command:
var PersonalId = await AsyncStorage.getItem('userData').userId;
because the item from the AsyncStorage is a string, I know this because I got this info from the second line of my code.
console.log(typeof PersonalId);
How can I access the special key "userId" inside my item "userData" and not the whole item itself? I cant work with the item anyways because its a string, I can not treat it as an object and thats my problem.
Thank you for reading and helping out!
You need to first parse value you are getting from the AsyncStorage into a JSON object using JSON.parse(). Try this implementation.
const get_data = async () => {
const userData = await AsyncStorage.getItem("userData");
const userObject = userData !== null ? JSON.parse(userData) : {};
const personalId = userObject.userId;
console.log(personalId);
};
You are forgetting that you stringified the JSON before saving it to storage.. so you are getting string when you read it. Simply JSON.parse the returned string and you should be on your way.
const userData = await AsyncStorage.getItem('userData');
const personalId = JSON.parse(userData).userId;
You should also wrap the above code in a try-catch to make sure you catch errors when invalid data is tried to be parsed and it throws an error.

Appended data to formData in node.js...the data which i am posting to my api is always showing null?

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 connect loop data to pdfgeneratorapi with wix corvid?

I'm generating PDF by using https://pdfgeneratorapi.com/.
Now I can show data one by one using this code.Can any one give me suggestion how can show all data with loop or any other way?
This below photos showing my template from pdfgenerator .
This is the code I'm using to generate PDF
let communicationWay1=[
{0:"dim"},
{1:"kal"}
];
let cstomerExpence1=[
{0:"dim"},
{1:"kal"}
];
let title="test";
let names="test";
let phone="test";
let email="test";
let maritalStatus="test";
let city="test";
let other="test";
const result = await wixData.query(collection)
.eq('main_user_email', $w('#mainE').text)
.find()
.then( (results) => {
if (results.totalCount>0) {
count=1;
// title=results.items[1].title;
names=results.items[0].names;
email=results.items[0].emial;
phone=results.items[0].phone;
maritalStatus=results.items[0].maritalStatus;
city=results.items[0].city;
other=results.items[0].cousterExpenses_other;
title=results.items[0].title;
communicationWay=results.items[0].communicationWay;
cstomerExpence=results.items[0].cstomerExpence;
}
if (results.totalCount>1) {
names1=results.items[1].names;
email1=results.items[1].emial;
phone1=results.items[1].phone;
maritalStatus1=results.items[1].maritalStatus;
city1=results.items[1].city;
other1=results.items[1].cousterExpenses_other;
title1=results.items[1].title;
communicationWay1=results.items[1].communicationWay;
cstomerExpence1=results.items[1].cstomerExpence;
}
} )
.catch( (err) => {
console.log(err);
} );
// Add your code for this event here:
const pdfUrl = await getPdfUrl
({title,names,email,phone,city,maritalStatus,other,communicationWay,cstomerExpence,title1,
names1,email1,phone1,city1,maritalStatus1,other1,communicationWay1,cstomerExpence1
});
if (count===0) { $w("#text21").show();}
else{ $w("#downloadButton").link=wixLocation.to(pdfUrl);}
BELOW CODE IS BACKEND CODE/JSW CODE.
Also I want to open pdf in new tab. I know "_blank" method can be used to open a new tab.But I'm not sure how to add it with the url
import PDFGeneratorAPI from 'pdf-generator-api'
const apiKey = 'MYKEY';
const apiSecret = 'MYAPISECRET';
const baseUrl = 'https://us1.pdfgeneratorapi.com/api/v3/';
const workspace = "HELLO#gmail.com";
const templateID = "MYTEMPLATEID";
let Client = new PDFGeneratorAPI(apiKey, apiSecret)
Client.setBaseUrl(baseUrl)
Client.setWorkspace(workspace)
export async function getPdfUrl(data) {
const {response} = await Client.output(templateID, data, undefined, undefined, {output: 'url'})
return response
}
Just put it in a while loop with a boolean condition.
You can create a variable, for example allShowed, and set its value to False. After that, create another variable, for example numberOfDataToShow, and set it as the number of elements you want to display. Then create a counter, countShowed, initialized with 0 as its value.
Now create a while loop: while allShowed value is False, you loop (and add data).
Everytime a piece of your data is showed, you increment the value of countShowed (and set it to go on adding/showing data). When countShowed will have the exact same value of numberOfDataToShow, set allShowed to True. The loop will interrupt and all your data will be showed.
You would need to use the Container or Table component in PDF Generator API to iterate over a list of items. As #JustCallMeA said you need to send an array of items. PDF Generator API now has an official Wix Velo (previously Corvid) tutorial with a demo page: https://support.pdfgeneratorapi.com/en/article/how-to-integrate-with-wix-velo-13s8135

how to access json data os asyncStorage function

I am using AsyncStorage to store data. Here is my function of storing data :
const profile = { userId, name, email };
await AsyncStorage.setItem('userProf', JSON.stringify(profile));
I have a problem when I try to access the data , if I console.log:
async componentWillMount(){
const profile = await AsyncStorage.getItem('userProf');
console.log(profile);
}
{"userId":"jefla3E0tjcJHhHKJK45QoIinB2","name":"egfgege","email":"ergeg#egrge.com"}
Now if I am willing to get only email value , I have tried with:
console.log(profile.email);
console.log(profile[0].email);
None of them worked, I get undefined as output, could you please help.
As AsyncStorage take and returns a string you will need to parse the string into json. You're already using JSON.stringify to save your object, you need to do the reverse operation to get it back to being an object.
const savedProfile = await AsyncStorage.getItem('userProf');
const profile = JSON.parse(savedProfile);
Then you should be able to access it the properties as you normally would, for example
const userId = profile.userId;
const email = profile.email;
const name = profile.name;
You may want to make sure that you perform a check that the returned value from AsyncStorage isn't null, as that will cause problems for you. Also await functions can throw, so you should make sure that you wrap your call to AsyncStorage in a try/catch
async componentWillMount(){
try {
const savedProfile = await AsyncStorage.getItem('userProf');
// you should check that the savedProfile is not null here
const profile = JSON.parse(savedProfile);
const userId = profile.userId;
const email = profile.email;
const name = profile.name;
} catch (err) {
console.warn(err);
}
console.log(profile);
}
When storing the value with AsyncStorage.setItem( ... ), you use JSON.stringify to convert the complete object into a String. This means, if you want to have a "normal" Object back (to use the dot operator), you have to use JSON.parse:
const profile = await AsyncStorage.getItem('userProf');
console.log(JSON.parse(profile));

Categories