schedule.scheduleJob('0 0 4 * * *',
function (fireDate) {
console.log(`fireDate: ${fireDate}`);
console.log(`now: ${new Date()}`);
resetUserData()
.then(result => {
console.log(`data removed at ${new Date()}`);
console.log('result:\n', result);
})
.catch(reason => {
console.error(`removing data failed at ${new Date()}`);
console.error(`reason: ${reason}`);
});
});
function resetUserData(){
return db('users')
.select('water', 'exercise', 'sleep', 'breaks', 'daily_points')
.del()
}
The reset function data should delete data based on the .select? It's instead deleting the entire user.
Related
This might be a silly question, but how do I get data if I saved the state using prevState.
I am trying to retrieve data from database and send that data through navigation.
const [dataFromDatabase, setDataFromDatabase] = useState('');
const retrieveFromDatabase = () => {
db.transaction(
tx => {
tx.executeSql("SELECT * FROM PreLoveeedTable",
[],
(_, { rows }) => {
console.log("ROWS RETRIEVED");
// clear data currently stored
setDataFromDatabase('');
let entries = rows._array;
entries.forEach((entry) => {
setDataFromDatabase(prev => prev + `${entry.id}, ${entry.image}, ${entry.title}, ${entry.price}, ${entry.description}\n
});
},
(_, result) => {
console.log('SELECT failed!');
console.log(result);
}
)
}
);
}
{dataFromDatabase} will give me the whole entire data in the database.
But wanted to have each entry in the Database. For example entry for title.
I have been stuck on this for a while now and would be appreciated it if i can get a hint.
I'm learning vuejs and I'm doing a weather app, the goal is to rank cities with an index (humidex). I fetch weather information by API (axios) in order to collect data from several cities. I want to auto update data every x minutes, problem : some of my results are duplicated (the new data don't replace the old one).
I tried to set an unique key (based on latitude and longitude) for each item, it works for several results but not for all.
data () {
return {
items:[],
show: false,
cities: cities,
newCity:''
}
},
components: {
Item
},
computed: {
sortHumidex() {
return this.items.slice().sort((a,b) => {
return this.getHumidex(b) - this.getHumidex(a) || b.current.temp_c - a.current.temp_c
})
}
},
methods: {
addCity() {
if (this.newCity.trim().length == 0) {
return
}
this.cities.push(this.newCity)
this.newCity = ''
},
getHumidex: (el) => {
const e = 6.112 * Math.pow(10,(7.5*el.current.temp_c/(237.7+el.current.temp_c)))
*(el.current.humidity/100)
return Math.round(el.current.temp_c + 5/9 * (e-10))
},
indexGeo: (e) => {
const lat = Math.round(Math.abs(e.location.lat))
const lon = Math.round(Math.abs(e.location.lon))
return lat.toString() + lon.toString()
},
getApi: function () {
const promises = [];
this.cities.forEach(function(element){
const myUrl = apiUrl+element;
promises.push(axios.get(myUrl))
});
let self = this;
axios
.all(promises)
.then(axios.spread((...responses) => {
responses.forEach(res => self.items.push(res.data))
}))
.catch(error => console.log(error));
}
},
created() {
this.getApi()
this.show = true
}
}
The render when I update API :
By pushing to the existing array of items, you have to deal with the possibility of duplicates. This can be eliminated simply by replacing items every time the API call is made.
Replace:
responses.forEach(res => self.items.push(res.data))
with:
self.items = responses.map(res => res.data)
I’m trying to update the notification count in my database.
I’m doing this by creating a set, which I add a UID to when I want to add to the notification count and removes a UID from the set when I want to subtract from the notification count.
I then take the size of the set and update the notification count.
the updateNotificationCount function is triggered by a lower order component.
However I can only get the database to update when isNewMatch is true. Why won’t it update the database when isNewMatch is false?
state = {notificationSet: new Set()}
updateNotificationCount = (uid, isNewMatch) => {
if (isNewMatch) {
this.setState(({ notificationSet }) => ({
notificationSet: new Set(notificationSet).add(uid)
}));
}
else {
this.setState(({ notificationSet }) => {
const newNotificationSet = new Set(notificationSet);
newNotificationSet.delete(uid);
return {
notificationSet: newNotificationSet
};
});
};
}
You don't need to do new Set() every time because you already initialize the state with new Set() so now you just do as follow:
state = {notificationSet: new Set()}
updateNotificationCount = (uid, isNewMatch) => {
let notificationSet;
if (isNewMatch) {
notificationSet=this.state.notificationSet;
notificationSet.add(uid);
this.setState({
notificationSet: notificationSet
});
} else {
notificationSet=this.state.notificationSet;
notificationSet.delete(uid);
this.setState({
notificationSet : notificationSet
});
};
}
I'm having am issue with an array that seems to be getting populated with my mongoose code by itself. It's making it impossible to populate the array with modified values.
Here's the code:
router.get('/in-progress', function(req, res) {
console.log('exporting');
var dataset = [];
Intake.find({}, function(err, intakes) {
if(err){
console.log(err);
} else {
/*intakes.forEach(function(intake) {
dataset.push(
{
//requestName: intake.requestName,
requestName: 'Request Name',
status: intake.phase
}
)
});*/
return dataset;
}
}).then((dataset) => {
console.log(dataset);
const report = excel.buildExport(
[
{
heading: inProgressHeading,
specification: inProgressSpec,
data: dataset
}
]
);
res.attachment('requests-in-progress.xlsx');
return res.send(report);
});
});
As you can see, the logic to push data to "dataset" is commented out, but the console log is logging every Intake that I have in the MongoDB database. Does anyone know what I am doing wrong so that I can push my own values into "dataset"?
I need to fetch a particular class (say Class A) records corresponding to each user in my parse server, when queried with admin role which have access to all the records in that particular class (Class A).
How can I do that?
Quick help would be greatly appreciated. :-)
I'm assuming that you want these records on the client, but the client doesn't have "permission" to get all class a records?
If I've got the problem right, then here's a solution. Create a cloud code function that can use the master key to query objects of class a.
// this is the cloud function that you can call with
// whichever client SDK you are using....
const fetchClassA = function (request, response) {
const result = [];
const userId = request.params.fetchForUser;
// the test here should be against role, just an example....
if (request.user.get('username') !== 'admin') {
response.error('you are not authorized.');
return;
}
if (!userId) {
response.error('no user supplied');
return;
}
const user = new Parse.User();
user.id = userId;
new Parse.Query('ClassA')
.equalTo('user', user)
// depending on the use case, you may want to use
// find here instead?
.each((object) => {
result.push(object);
}, { useMasterKey: true })
.then(() => response.success(result))
.catch(response.error);
}
// the rest of this is just a unit test to "lightly" test
// our cloud function....
describe('fetch record with a cloud function', () => {
const userA = new Parse.User();
const userB = new Parse.User();
beforeEach((done) => {
userA.setUsername('userA');
userA.setPassword('abc');
userB.setUsername('userB');
userB.setPassword('def');
Parse.Object.saveAll([userA, userB])
.then(() => Parse.Object.saveAll([
new Parse.Object('ClassA').set('user', userA),
new Parse.Object('ClassA').set('user', userA),
new Parse.Object('ClassA').set('user', userA),
new Parse.Object('ClassA').set('user', userB),
new Parse.Object('ClassA').set('user', userB),
new Parse.Object('ClassA').set('user', userB),
]))
.then(() => Parse.User.signUp('admin', 'foo'))
.then(done)
.catch(done.fail);
});
it('should fetch class a', (done) => {
Parse.Cloud.define('fetchClassA', fetchClassA);
Parse.Cloud.run('fetchClassA', { foo: 'bar', fetchForUser: userA.id })
.then(result => expect(result.length).toBe(3))
.then(done)
.catch(done.fail);
});
});