MongoDB Update Method Not Working - javascript

Hoping someone out there could tell me where I am going wrong with this update method:
changeTaskDetails: function(singleID,detailsTarget){
TaskDetails.update({
_id: singleID,
}, {
$set:{
projectType: detailsTarget,
}
});
console.log(singleID);
},
Here is the event:
'submit #editTaskDetails'(event){
event.preventDefault();
var id = FlowRouter.getParam('taskId');
const singleDetailsUpdate = Tasks.findOne({_id:id});
const singleID = singleDetailsUpdate._id;
const target = event.target;
const facilityTarget = target.facilityName.value;
const inspectorTargetName = target.detailsinspector.value;
const inspectorIdTarget = target.inspectorid.value;
const detailsTarget = target.detailstype.value;
const dateTarget = target.TaskDate.value;
console.log(singleID)
Meteor.call("changeTaskDetails", singleID,detailsTarget);
},
I can get the 2 props to log...but its not updating the DB. No errors in either console.

I figured it out! I had a session variable controlling when you could (or could not) see the update form. For one reason or another the form crapped out when inside of this area. When I removed the session, and added the form to the main template...it worked!

Related

LocalStorage doesn't persist the data after page refresh

I have a problem with the getItem of my localStorage in my React Form. I put a onChange attribute:
<div className = 'InputForm' onChange={save_data}>
I found the setItem function to store the data in. Here is the function:
function save_data(){
let textarea = document.querySelectorAll("textarea")
let input = document.querySelectorAll("input[type='text']")
let saved_fields = []
textarea.forEach(x => {
saved_fields.push({
key: x.className,
value: x.value
})
})
input.forEach(x => {
saved_fields.push({
key: x.className,
value: x.value
})
})
localStorage.setItem("saved_data", JSON.stringify(saved_fields))
}
My main problem is that I don't find a way to put the data back to the page after the page reload. I just found out how to persist all my inputs in the console:
window.onload = dataLoad();
function dataLoad () {
let show_saved_data = localStorage.getItem("saved_data");
console.log('show_saved_data:',JSON.parse(show_saved_data));
}
Can you guys help me find the retrieve/persist data function?
Edit : Here is the html of the form, i use props from another component. I don't know if this can change the function i need to use.
<InputFields
stateKey = 'contactInfo'
key = {props.contactInfo.id}
completedFields = {props.contactInfo}
templateFields = {props.templates.contactInfo}
onDataEntry = {props.onDataEntry}
newField = {props.newField}
/>
Can we have your HTML form to help you? You should not identify your inputs / textareas by their className.
After that, by using ID as identifiers for your input / textarea, you just have to do it in reverse:
Get your input/textarea list
forEach items, set the value based on the ID
function dataLoad () {
var show_saved_data = localStorage.getItem("saved_data");
var inputList = JSON.parse(show_saved_data);
inputList.forEach(x => {
document.getElementById(x.key).setAttribute('value', x.value);
})
}
Giving us your complete HTML/JS will be easier to give you a complete solution.

Prevent duplicate action when multiple storage keys are modified

I've been learning JavaScript for about a month now, and right now I’m working on a little project (Shopping Cart) to dive into storage events. I’ve successfully managed to store a few keys from “tab1” into the local storage and retrieve them from “tab2”. However, I came across a particular “problem”, which I’ve been struggling with for the last couple of days.
On “tab1” I have five keys that are being stored in localStorage. on “tab2” I need to complete an action (create an HTML element) every time the localStorage changes. The problem is that the action is being triggered once for every key that’s changed. In other words, I keep getting 5 duplicate HTML elements.
I’ve spent many hours searching for answers on forums, YouTube videos, blogs and of course here. So far no luck. I’ve also been reading the documentation on localStorage, but since I’m new at this, it’s not very clear for me.
I hope you can help find a solution or understand why I keep getting these duplicate actions.
This is an example of the code I have so far:
let itemList = document.getElementById("itemList");
let summaryItem = document.getElementById("summaryItem_01");
let summaryImage = document.getElementById("itemImage_01");
let summaryName = document.getElementById("item_Name_01");
let summaryModel = document.getElementById("itemModel_01");
let summaryQuantity = document.getElementById("detailQuantityDisplay_01");
let summaryPrice = document.getElementById("itemPriceAmount_01");
//Gets localStorage info on page load and feeds summaryItem fields.
window.addEventListener("load", () => {
let itemImage = localStorage.getItem("modalItemImage");
let itemName = localStorage.getItem("modalItemName");
let itemModel = localStorage.getItem("modalItemModel");
let itemQuantity = localStorage.getItem("modalItemQuantity");
let itemPrice = localStorage.getItem("modalItemUnitPrice");
//Prints localStorage info to summaryItem element.
summaryImage.setAttribute("src", itemImage);
summaryName.innerText = itemName;
summaryModel.innerText = itemModel;
summaryQuantity.value = itemQuantity;
summaryPrice.innerText = itemPrice;
});
//This is where I'm getting the duplicate action
window.addEventListener("storage", () => {
let a = document.createElement("article");
itemList.appendChild(a);
});
UPDATE:
After MauriceNino's suggestion, I ended up with this code and it worked perfectly:
//Tab1
let modalItem = {
modalItemImage: displayModalImage.innerHTML.slice(10, -2),
modalItemName: displayModalName.innerText,
modalItemModel: displayModalModel.innerText,
modalItemQuantity: displayModalQty.value,
modalItemUnitPrice: displayModalPrice.innerText,
modalItemTotal: displayModalTotal.innerText,
};
localStorage.setItem("modalItem", JSON.stringify(modalItem));
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Tab2
//Gets localStorage info from modal
let data = JSON.parse(localStorage.getItem("modalItem"));
let dataArray = Object.values(data);
let itemImage = dataArray[0];
let itemName = dataArray[1];
let itemModel = dataArray[2];
let itemQuantity = dataArray[3];
let itemPrice = dataArray[4];
//Prints localStorage info to summaryItem element.
summaryImage.setAttribute("src", itemImage);
summaryName.innerText = itemName;
summaryModel.innerText = itemModel;
summaryQuantity.value = itemQuantity;
summaryPrice.innerText = itemPrice;
//Creates new summaryItem when there's a chnage on localStorage.
window.addEventListener("storage", () => {
let a = document.createElement("article");
itemList.appendChild(a);
});
You could just save it as one element like so:
//Gets localStorage info on page load and feeds summaryItem fields.
window.addEventListener("load", () => {
// Get all the data in a single statement
let { itemImage, itemName, itemModel, itemQuantity, itemPrice }
= localStorage.getItem("modalItem");
//Prints localStorage info to summaryItem element.
summaryImage.setAttribute("src", itemImage);
// ...
});
//Will be called only once now
window.addEventListener("storage", () => {
let a = document.createElement("article");
itemList.appendChild(a);
});
// This is where you are saving your localStorage settings
localStorage.setItem("modalItem", {
itemImage: 'image',
itemName: 'name',
itemModel: 'model',
itemQuantity: 2,
itemPrice: 3
});

Delete an entry from firebase realtime database with a click of a button

I need help on how to remove a firebase entry
I have the following code in the javascript:
document.getElementById('deleteDriver_btn').onclick = function() {
firebase.database().ref('drivers').child('driver_num').on('value', function(driverSnapshot) {
var driverChildSnapshot = driverSnapshot.val();
var queryRef = firebase.database().ref('drivers').orderByChild('driver_num').equalTo(dataRow);
queryRef.remove();
});
};
I get an error saying that queryRef.remove() is not a function.
Firebase entry goes like:
---driver
--AKSJDIWDKSADKAWsdak <---- want to delete this and the data underneath
-driver_num
-first_name
-last_name
--akdjwoajdksafksndjiw <---- want to retain this
-driver_num
-first_name
-last_name
Okay I found my answer thanks to the hint #TommyBs sent about the references. I just query to extract the key and then initiate .ref().remove()
document.getElementById('deleteDriver_btn').onclick = function() {
var refe = firebase.database().ref("drivers");
var diskey = "";
refe.orderByChild("driver_num").equalTo(dataRow).on("child_added", function(snapshots)
{
diskey = snapshots.key;
});
firebase.database().ref("drivers/" + diskey).remove();
};

Update ONLY some fields of an object in IndexedDB

For example:
object1(1) = {
name: 'Rhodok Sergeant',
speciality: 'Hand to hand battle'
}
then I want to update only the speciality field, into:
object1(1) = {
name: 'Rhodok Sergeant',
speciality: 'Long range battle'
}
Thank you.
This is possible using following steps -
fetch the item first using idbcursor
update that item
call cursor.update to store updated data in indexedb.
An example code is -
const transaction = db.transaction(['rushAlbumList'], 'readwrite');
const objectStore = transaction.objectStore('rushAlbumList');
objectStore.openCursor().onsuccess = function(event) {
const cursor = event.target.result;
if (cursor) {
if (cursor.value.albumTitle === 'A farewell to kings') {
const updateData = cursor.value;
updateData.year = 2050;
const request = cursor.update(updateData);
request.onsuccess = function() {
console.log('data updated');
};
};
cursor.continue();
}
};
Check out this link for more info - https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/update
Note:- In above code, i am looping through all records which is not efficient in case you want to fetch the particular record based on some condition. So you can use idbKeyRange or some other idb query alternative for this.
you cannot do partial updates, you can only overwrite an entire object
read the object in from memory, change it, and then write it back

how to clone the mongoose query object in javascript

I am facing the problem of clone of the mongoose query object .Javascript the copy the one object into another object by call-by-ref but in my project there is scenario i need to copy one object into another object by call-by-value.
var query=domain.User.find({
deleted: false,
role: role
})
var query1=query;
I have the scenario change in the query object is not reflected in query1. I google and try so many way to clone the object but it does't work.The query object is used in another function for pagination and query1 object is used for count query.
1.I used to Object.clone(query1) error Object.clone is not function
2.I used Object.assign(query1) but it does't works fine.
3.I used other so many ways can anybody help me to sort this problem
Alternative solution using merge method:
const query = domain.User.find({
deleted: false,
role: role
}).skip(10).limit(10)
const countQuery = query.model.find().merge(query).skip(0).limit(0)
const [users, count] = await Promise.all([query, countQuery.count()])
you are trying to clone a cursor, but it is not the right approach, you probably just need to create another
like this:
var buildQuery = function() {
return domain.User.find({
deleted: false,
role: role
});
};
var query = buildQuery();
var query1 = buildQuery();
This is work for me:
const qc = sourceQuery.toConstructor();
const clonedQuery = new qc();
This code work in pagination function where sourceQuery passed as parameter and i dont known what models used. Also it work with aggregations and complex queries.
public async paging(
query: mongoose.DocumentQuery<mongoose.Document[], mongoose.Document>,
params,
transformer: any = null
) {
let page = Number(params.page);
if (!page) page = 1;
let page_size = Number(params.count);
if (!page_size) page_size = 100;
const qc = query.toConstructor();
const cq = new qc();
return cq.countDocuments().exec()
.then(async (total) => {
const s = params.sort;
if (s) {
query.sort(s);
}
query.limit(page_size);
query.skip(page_size * (page - 1));
let results = await query.exec();
if (transformer) {
results = await Promise.all(results.map((i) => transformer(i)));
}
const r = new DtoCollection();
r.pages = Math.ceil(total / page_size);
r.total = total;
(r.results as any) = results;
return r;
});
}
Sergii Stotskyi's answer works just fine and is very elegant, except that count is deprecated.
countDocuments or estimatedDocumentCount should be used instead.
However, this causes the error the limit must be positive. We can walk around this by set limit to a large integer.
const query = domain.User.find({
deleted: false,
role: role
}).skip(10).limit(10)
const countQuery = query.model.find().merge(query).skip(0).limit(Number.MAX_SAFE_INTEGER)
const [users, count] = await Promise.all([query, countQuery.countDocuments()])
Since mongoose v6 you can use Query.prototype.clone
E.g. for your code snippet:
const query = domain.User.find({
deleted: false,
role: role
})
const query1 = query.clone();

Categories