I have an array(tasks) of objects in my model. I want to delete a task from the array using sequelize and save back to db(postgresql). Here i am trying to find the index of the task which will deleted and update the tasks in my db. but change is not visible to my db. Here is my code:
var idx=0;
for(var i=0;i<user.tasks.length;i++){
if(user.tasks[i].task_id==req.params.task_id){
idx=i;
break;
}
}
user.tasks.splice(idx,1);
user.update({
tasks:user.tasks
}).then((user)=>{
res.redirect("/seq/task/allTask")
})
})
let user_id = 2
let pinned_by_user = [1,2,4,5]
let i = pinned_by_user.indexOf(user_id);
if (pinned_by_user > -1)
{
pinned_by_user.splice(i, 1);
}
ViewLog.update({ 'pinned_by_user': db.sequelize.fn('array_remove',db.sequelize.col('pinned_by_user'), user_id) },{ 'where': { 'questionId': question_id } })
inside user.update() use this {tasks:Sequelize.fn('array_remove',Sequelize.col('tasks'),JSON.stringify(user.tasks[i]))}
Related
I'm using MERN stack for my program with mongoose for accessing the database. I have a collection called Movies and I wanted to edit multiple objects in an array within this collection. This is what the Movie Schema contains in my database:
I wanted to edit multiple objects in the 2D array within seats and to change isReserved to True.
I just used findOne in accessing the data since I still don't know how to update the objects that I want to access.
app.post('/confirm/:movieId/:timeId', (req, res) => {
const movieId = req.params.movieId;
const timeId = req.params.timeId;
const selectedSeats = req.body;
// console.log("in confirm DB ");
// console.log(selectedSeats);
let getSeats;
let getTimeSlots;
const length_timeId = timeId.length;
Movies.findOne({ movieId }, (err, movie) => {
console.log("INSIDE");
getTimeSlots = movie['timeslots'];
let index = timeId.substring(1, length_timeId);
//get the seats
getSeats = getTimeSlots[parseInt(index)-1];
//loop through seats
console.log("PRINTING GET SEATS");
console.log(getSeats);
for(var i=0; i<selectedSeats.length; i++) {
let row = parseInt(selectedSeats[i] / 5);
let id = selectedSeats[i] % 5;
console.log(getSeats["seats"][row][id]);
}
})
})
I already accessed the objects that I want to edit as that code displays this on my terminal:
Would really appreciate some tips on how to update the isReserved status. Thanks!
Do you specify the timeslot and seat by an id or by the index within the array? If you use the index then solution is quite simple
const key = "timeslots." + req.params.timeId + ".seats." + req.body + ".isReserved";
var upd = {};
upd[key] = true;
db.Movies.updateOne({ movieId: req.params.movieId }, { $set: upd })
If your code uses the id then you have to work with array filters, see Update Nested Arrays in Conjunction with $[], so similar to this
db.Movies.updateOne(
{ movieId: req.params.movieId },
{ $set: { "timeslots.$[slot].seats.$[seat].isReserved": true } },
{ arrayFilters: [ { "slot.id": req.params.timeId } , { "seat.id": req.body } ] }
)
I'm working on a simple to-do list with vanilla js. I've managed to add the input to local storage, but have not been able to add the style changes(check strike through) to local storage, nor can I figure out how to remove one item at a time from storage. I have been able to clear all, just unable to remove each item separately. Below is my code, any advice is greatly appreciated.
//local storage setup
let saved = window.localStorage.getItem(input.value);
if (saved) {
list.innerHTML = saved;
}
//handle input submit
function handleSubmitForm(e) {
e.preventDefault();
let input = document.querySelector('input');
if (input.value != '') {
addTodo(input.value);
}
input.value = '';
window.localStorage.setItem(input.value, list.innerHTML);
}
//check off todo
function checkTodo(e) {
let item = e.target.parentNode;
if (item.style.textDecoration == 'line-through') {
item.style.textDecoration = 'none';
} else {
item.style.textDecoration = 'line-through';
}
window.localStorage.setItem(item);
}
//delete todo
function deleteTodo(e) {
let item = e.target.parentNode;
item.addEventListener('transitionend', function () {
item.remove();
});
item.classList.add('todo-list-item-fall');
window.localStorage.removeItem(item);
}
JavaScript Storage is a key-value pair. Just use a string-based key so you can remove, edit or read it easily.
// Set todo item
localStorage.setItem("todo1", "Stand-up meeting 9.15am");
// Read todo item
localStorage.getItem("todo1");
// Delete todo item
localStorage.removeItem("todo1");
It's better if you can save it as a JSON string because you can mark it as completed without delete, so you can find completed tasks too.
// Saving todo item as a JSON string
localStorage.setItem("todo1", JSON.stringify({ text: "Stand-up meeting 9.15am", completed: false }));
// Read it
const todo = JSON.parse(localStorage.getItem("todo1"));
// You can read the text
console.log(todo.text);
// Also you can mark it as completed and save it back
todo.completed = true;
localStorage.setItem("todo1", JSON.stringify(todo));
Storing object in localStorage is a tricky job.
Everything you store in the local or session storage is of type string
you can create an object like
item = {
value : ANY_VALUE
}
and save it in your localStorage using JSON.stringify
localStorage.setItem(`item`,JSON.stringify(item))
now when you want to update the item just update the object and again set using the ablove syntax
To access the saved item from the local storage use JSON.parse
yourItemObject = JSON.parse(localStorage.getItem())```
You can access values now using yourItemObject .value
It appears you're passing the whole HTML element (it passed as an object) inside the removeItem function. you need to pass the key instead.
try localStorage.removeItem(item.innerText);
If you are working with lists in localStorage. I would use something like this basic example:
function addTodo(key, item){
var list = getTodo(key);
list.push(item);
localStorage.setItem(key, JSON.stringify(list) );
}
function getTodo(key){
try{
var rawList = localStorage.getItem(key);
return JSON.parse(rawList) || [];
}
catch(e){
return [];
}
}
function removeTodo(key, id){
var list = getTodo(key);
var newlist = list.filter( function(item){
return item.id != id;
});
localStorage.setItem(key, JSON.stringify(newlist) )
}
function emptyTodo(key){
localStorage.removeItem(key);
}
addTodo('list', {
id: 1,
text: 'do shopping'
});
addTodo('list', {
id: 2,
text: 'study'
});
console.log( getTodo('list') );
removeTodo('list', 1);
console.log( getTodo('list') )
emptyTodo('list');
Trying to iterate through a database and add the values to an array in Node.js. When I try to push the items based on their column name ('account name':res.rows[i].account_name), I get an "undefined" error.
If I push the item in with the "accountList.push(res.rows[i])" line, all the data goes into the object but it isn't labelled.
I have a feeling that this is something to do with the async nature of Node.
What am I doing wrong?
const query = {
name: "getDB",
text: "select * from smartsneakers",
rowMode:'array',
}
pool.query(query, (err,res) => {
if (err) {
res.status(500).json({"status_code": 500, "status_message": "internal server error"});
} else {
for (let i = 0; i < res.rows.length; i++) {
console.log(res.rows[i].account_name)
//accountList.push(res.rows[i]);
var account = {
'account name':res.rows[i].account_name,
}
accountList.push(account);
}
//console.log(accountList);
console.log(accountList[0]);
}
})
//close connection
pool.end();
It was because I was using "rowMode:'array'" so it was outputting the whole row.
The question led me to the answer - thanks!
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
I have a .json file on my hard drive with about 70 entries.
This is the model i'm using:
var tweetModel = mongoose.model('tweet', {
"correct":Boolean,
"text": String,
"id":{type:String, unique:true},
"user":{
"atNamn":String,
"namn":String,
"bild":String,
"id":String
}
});
Some of the tweets are duplicates and therefore share the same "id" attribute. I want to filter these out when adding. At the moment i just go through the JSON like this.
var JSONData = require("../public/data/jsondata")
for(key in JSONData){
new tweetModel(JSONData[key]).save(function(err,doc){
if(err){console.log(err)}
else{
console.log(doc);
}
})
}
If i run this one time, they ALL get added. If i do it one more time a duplicate error is thrown. I want it to check for duplicates BEFORE adding!
Use a simple JS object to keep track of which id values you've already seen:
var seenIds = {};
for(key in JSONData){
var json = JSONData[key];
if (!seenIds[json.id]) {
seenIds[json.id] = true;
new tweetModel(json).save(function(err,doc){
if(err){console.log(err)}
else{
console.log(doc);
}
});
}
}