Hi i have a weird javascript issue.Here's my code I am not able to send these keys in my designOrder object. My Object does not have these fronImage and backImage keys that i am sending in my code.
let designOrder = await dbCall();
let allImages = []
allImageIds.push(designOrders.frontImageId);
allImageIds.push(designOrders.backImageId);
allImages = await dbCall();
let allImagesHash = {};
allImages.forEach(obj) => {
obj.image = JSON.parse(image)
allImagesHash[image.id] = image;
}
if(designOrder.backImageId){
designOrder.backImage = allImagesHash[designOrder.backImageId]
}
// if i do console.log("1", designOrder.backImage) it will log the designOrder.backImage
if(designOrder.frontImageId){
designOrder.frontImage = allImagesHash[designOrder.frontImageId]
}
// if i do console.log("2", designOrder.frontImage) it will log the designOrder.backImage
// but while console.log("3", designOrder) it will not show the backImage and frontImage keys
return designOrder;
It actually solved it after the first dbCall() i have added this line of code and it worked.
designOrder = designOrder.toJSON();
toJson function is defined within the mongoose schema.
Related
I have this script that takes data from a JSON with almost 100 data, then uses this data to bring the weather from an API and after that, inserts this data into an object (using a for for creating my 100 objects), I would like to add the objects that have a temperature > 99 in one array and the ones that have a temperature < 99 into another I have tried this way but doesn't seem to work, sorry if it's a super fool mistake that I can't see, thanks for your help!
This is my script:
async function calcWeather(){
const info = await fetch('../json/data.json')
.then(function(response) {
return response.json()
});
for (var i in info) {
const _idOficina = info[i][0].IdOficina
const _nombreOficina = info[i][0].NombreOficinaSN
const _zona = info[i][0].Zona
const _estado = info[i][0].NombreEstado
const lat = info[i][0].latjson
const long = info[i][0].lonjson
const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`
fetch(base)
.then((responses) => {
return responses.json()
})
.then((data) => {
// console.log(data)
var myObject = {
Id_Oficina: _idOficina,
Latitud: data.coord.lat,
Longitud: data.coord.lon,
Ciudad: data.name,
Estado: _estado,
Zona: _zona,
Nombre_Oficina: _nombreOficina,
Temperatura: data.main.temp,
Descripcion: data.weather[0].description
};
// validation
if (myObject.Temperatura < 99){
var lstValid = [];
function pushValid(){
lstValid.push(myObject[i]);
}
pushValid();
console.log(pushValid())
}
});
}
};
Your array is local, so for every object you create new lstValid array with no previous data. The solution is to create the array before fetching the data or before the loop:
async function calcWeather(){
var lstValid = []; // HERE
const info = await fetch('../json/data.json')
.then(function(response) {
return response.json()
});
var lstValid = []; // OR HERE (ONLY ONE OF THEM)
for (...) {
...
}
You'll probably be best served by creating the array outside of that call since you're clearing it every run. Then simply add your object. Like Trincot's comment, i'm not sure what exactly you're indexing.
async function calcWeather(){
var lstValid = [];
....
if (myObject.Temperatura < 99){
lstValid[someindex] = myObject;
}
else{
lstNotValid[someOtherIndex] = myObject;
}
}
I'm using parse with javascript (vueJs) and i'm experiencing the following issue : when I destroy an object and then get all my data, the object is still in the result. However, if I look in my parse backend, the object has been deleted.
This is my code:
methods: {
getNotes: async function() {
console.log("\nGETTING ALL NOTES")
const Object = Parse.Object.extend("notes");
const query = new Parse.Query(Object);
query.equalTo("user", Parse.User.current());
query.descending("createdAt");
const results = await query.find();
for (let i = 0; i < results.length; i++) {
var temp = {}
const object = results[i];
temp.id = object.id
temp.note = object.get('note')
temp.date = object.get('createdAt')
this.notes.push(temp)
}
},
deleteNote: async function() {
const Object = Parse.Object.extend("notes");
const query = new Parse.Query(Object);
query.equalTo("objectId", this.selectedItem);
const results = await query.first();
if (results){
await results.destroy() // I wait for the object to be destroyed
await this.getNotes() //Then, I call (again) my function to get all notes ... but it still contains the deleted object !!
}else{
alert("There was a problem with the query")
}
}
}
Any ideas why this happens and how can I "check" when my parse database is up to date so that I can get the data again (without the removed object) ?
I have the following code:
const readDataFromSql = () => {
// going to have to iterate through all known activities + load them here
let sql = "[...]"
return new Promise((resolve, reject) => {
executeSqlQuery(sql).then((dict) => {
let loadedData = [];
for (let key in dict) {
let newItemVal = new ItemVal("reading hw", 7121, progress.DONE);
loadedData.push(newItemVal);
}
resolve(loadedData);
});
});
}
ItemVal implementation:
class ItemVal {
constructor(name, time, type) {
this.name = name
this.time = time
this.type = type
}
}
Let's assume that newItemVal = "reading hwj", 5081, progress.PAUSED when readDataFromSql() first runs.
readDataFromSql() is then again called after some state changes -- where it repulls some information from a database and generates new values. What is perplexing, however, is that when it is called the second time, newItemVal still retains its old properties (attaching screenshot below).
Am I misusing the new keyword?
From what I can see in your example code, you are not mutating existing properties but creating a new object with the ItemVal constructor function and adding them to an array, that you then return as a resolved promise. Are you sure the examples you give a correct representation of what you are actually doing
Given that, I'm not sure what could be causing the issue you are having, but I would at least recommend a different structure for your code, using a simpler function for the itemVal.
Perhaps with this setup, you might get an error returned that might help you debug your issue.
const itemVal = (name, time, type) => ({ name, time, type })
const readDataFromSql = async () => {
try {
const sql = "[...]"
const dict = await executeSqlQuery(sql)
const loadedData = dict.map((key) =>
ItemVal("reading hw", 7121, progress.DONE)
)
return loadedData
} catch (error) {
return error
}
};
If the issue is not in the function, then I would assume that the way you handle the data, returned from the readDataFromSql function, is where the issue lies. You need to then share more details about your implementation.
const readDataFromSql = async () => {
let sql = "[...]"
------> await executeSqlQuery(sql).then((dict) => {
Use the await keyword instead of creating a new promise.
I did some modification and found that below code is working correctly, and updating the new values on each call.
const readDataFromSql = () => {
return new Promise((resolve, reject) => {
let loadedData = [];
let randomVal = Math.random();
let newItemVal = new ItemVal(randomVal*10, randomVal*100, randomVal*1000);
loadedData.push(newItemVal);
resolve(loadedData);
});
}
Could you recheck if you are using below line in the code, as it will instantiate object with same properties again and again.
let newItemVal = new ItemVal("reading hw", 7121, progress.DONE);
You can modify your code as below to simplify the problem.
const readDataFromSql = async () => {
// going to have to iterate through all known activities + load them here
let sql = "[...]" // define sql properly
let result = await executeSqlQuery(sql);
let loadedData = [];
for (let row in result) {
let newItemVal = new ItemVal(row.name, row.time, row.type);
loadedData.push(newItemVal);
}
return loadedData;
}
class ItemVal {
constructor(name, time, type) {
this.name = name
this.time = time
this.type = type
}
}
What you are talking about is an issue related to Object mutation in Redux, however, you didn't add any redux code. Anyway, you might be making some mistake while recreating(not mutating) the array.
General solution is the use spread operator as:
loadedData = [ ...loadedData.slice(0) , ...newloadedData]
In Dropdown.js line 188 instead of console.log-ing your variable write debugger;
This will function as a breakpoint. It will halt your code and you can inspect the value by hovering your mouse over the code BEFORE the newItemVal is changed again.
I can see in your screenshot that the newItemVal is modified again after you log it.
Question: How do I store a large array full of objects, all of which have 5 properties and all except the id property must be updated. Further more, why won't the code below work and how can I format it to work with the main question?
Info I've viewed:
https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/openCursor
https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/createIndex
Note: I am aware of the setInterval and its inefficiency, it is for testing purposes so I do not have to click many times to check for a result.
<html>
<body>
<script type="text/javascript">
let count =0;
let storeBuilt = false;
const dbName = "the_name";
let version=82;
let storeName= "store82";
let storeBuilding= false;
setInterval(build,1000/24);
function build(){
hello()
}
function hello(){
let customerData = [];
for(let i=0;i<=50000;i++){
customerData.push({name:"bob",minX:random(),minY:random(),maxX:random(),maxY:random(),id:random()})
}
let request = indexedDB.open(dbName, version);
request.onsuccess= function(event){
let db = event.target.result;
let transaction = db.transaction( storeName,"readwrite").objectStore(storeName);
if( storeBuilding=== false&& storeBuilt=== false){
storeBuilding= true;
let additem = addData(customerData, transaction);
additem.onsuccess= function(e){storeBuilt=true}
} else if (storeBuilt=== true){
let updateitem= updateData(customerData, transaction);
}
};
request.onupgradeneeded = function(event) {
let db = event.target.result;
// Create an objectStore to hold information about our customers. We're
// going to use "ssn" as our key path because it's guaranteed to be
// unique - or at least that's what I was told during the kickoff meeting.
let objectStore = db.createObjectStore(storeName, {keyPath:"names",autoIncrement:true});
objectStore.createIndex("name","name",{unique:true});
// Use transaction oncomplete to make sure the objectStore creation is
// finished before adding data into it.
objectStore.transaction.oncomplete = function(event) {
// Store values in the newly created objectStore.
let customerObjectStore = db.transaction(storeName, "readwrite").objectStore(storeName);
}
};}
function random (){
return (Math.floor((Math.random() * 10) + 1))
}
function addData(data,transaction){
return transaction.add(data)
}
function updateData(data,transaction){
let openCursor = transaction.index("name").openCursor();
openCursor.onsuccess= function(event){
let cursor = event.target.result;
if (cursor){
alert (cursor);
for(let I in data){
let item = data[I];
if(item.id === cursor.value.id){
let updateProperty = cursor.value;
updateProperty.minX = item.minX;
cursor.update(updateProperty);
cursor.continue()
}
}
}{alert("none")}
}
}
function deleteData(data,transaction){
}
</script>
</body>
</html>
Not sure if I understand the problem clearly, but generally you will want to load the objects from the object store, modify each object's properties, and then store the objects in the object store. There are several ways to do this. One way is to use cursor.update, but I don't think you need to do this at all. Just overwrite the objects.
function storeThings(db, things, callback) {
var txn = db.transaction('store82', 'readwrite');
txn.oncomplete = callback;
var store = txn.objectStore('store82');
for(var thing of things) {
store.put(thing);
}
}
function open(callback) {
var request = indexedDB.open();
request.onsuccess = _ => callback(request.result);
}
var things = [{id:1}, {id:2}, {id:3}];
open(db => storeThings(db, things, _ => console.log('done')));
I am using IDBObjectStore.prototype.put to store the objects. The put method will either create or overwrite an object in the store. It will create a new object in the store when no matching object is found based on the keypath. It will replace an existing object in the store when a matching object is found.
In your case, you are using ssn string as a keypath. So, in other words, it will create new people if ssn not found, or overwrite people if ssn found. You just need to make sure that the ssn property is defined within each person object you pass to put, or indexedDB will complain.
I need to create a new array from iterating mongodb result. This is my code.
const result = await this.collection.find({
referenceIds: {
$in: [referenceId]
}
});
var profiles = [];
result.forEach(row => {
var profile = new HorseProfileModel(row);
profiles.push(profile);
console.log(profiles); //1st log
});
console.log(profiles); //2nd log
I can see update of profiles array in 1st log. But 2nd log print only empty array.
Why i couldn't push item to array?
Update
I think this is not related to promises. HorseProfileModel class is simply format the code.
const uuid = require("uuid");
class HorseProfileModel {
constructor(json, referenceId) {
this.id = json.id || uuid.v4();
this.referenceIds = json.referenceIds || [referenceId];
this.name = json.name;
this.nickName = json.nickName;
this.gender = json.gender;
this.yearOfBirth = json.yearOfBirth;
this.relations = json.relations;
this.location = json.location;
this.profilePicture = json.profilePicture;
this.horseCategory = json.horseCategory;
this.followers = json.followers || [];
}
}
module.exports = HorseProfileModel;
await this.collection.find(...)
that returns an array of the found data right? Nope, that would be to easy. find immeadiately returns a Cursor. Calling forEach onto that does not call the sync Array.forEach but rather Cursor.forEach which is async and weve got a race problem. The solution would be promisifying the cursor to its result:
const result = await this.collection.find(...).toArray();
Reference