Is there any equivalent to populate in parse-server - parse-server

I created subject like that
const subject = new Subject({
subject_name
});
subject.save();
and then I created Teacher
const teacher = new Teacher({
teacher_name:'teacher neme',
teacher_age:34,
subject:'wGvTu03HQd'
});
teacher.save();
when i try to get the teacher object using
let query = new Parse.Query(Teacher);
let a = await query.get(objectId);
console.log(a.get('subject'))
i get
ParseObjectSubclass { className: 'Subject', _objCount: 1, id: '8sB8uibifQ' }
is there is a way to get the data from the subject object without using
let query = new Parse.Query(Subject);
let a = await query.get(objectId);
since it has a relation with the Teacher, something like populate in mongoose?

Yes. You can use the include function:
let query = new Parse.Query(Teacher);
query.include('subject');
let a = await query.get(objectId);
console.log(a.get('subject'))
Reference: https://docs.parseplatform.org/js/guide/#relational-queries

Related

Write rows to BigQuery via nodejs BigQuery Storage Write API

It seems quite new, but just hoping someone here has been able to use nodejs to write directly to BigQuery storage using #google-cloud/bigquery-storage.
There is an explanation of how the overall backend API works and how to write a collection of rows atomically using BigQuery Write API but no such documentation for nodejs yet. A recent release 2.7.0 documents the addition of said feature but there is no documentation, and the code is not easily understood.
There is an open issue requesting an example but thought I'd try my luck to see if anyone has been able to use this API yet.
Suppose you have a BigQuery table called student with three columns id,name and age. Following steps will get you to load data into the table with nodejs storage write api.
Define student.proto file as follows
syntax = "proto2";
message Student {
required int64 id = 1;
optional string name = 2;
optional int64 age = 3;
}
Run the following at the command prompt
protoc --js_out=import_style=commonjs,binary:. student.proto
It should generate student_pb.js file in the current directory.
Write the following js code in the current directory and run it
const {BigQueryWriteClient} = require('#google-cloud/bigquery-storage').v1;
const st = require('./student_pb.js')
const type = require('#google-cloud/bigquery-storage').protos.google.protobuf.FieldDescriptorProto.Type
const mode = require('#google-cloud/bigquery-storage').protos.google.cloud.bigquery.storage.v1.WriteStream.Type
const storageClient = new BigQueryWriteClient();
const parent = `projects/${project}/datasets/${dataset}/tables/student`
var writeStream = {type: mode.PENDING}
var student = new st.Student()
var protoDescriptor = {}
protoDescriptor.name = 'student'
protoDescriptor.field = [{'name':'id','number':1,'type':type.TYPE_INT64},{'name':'name','number':2,'type':type.TYPE_STRING},{'name':'age','number':3,'type':type.TYPE_INT64}]
async function run() {
try {
var request = {
parent,
writeStream
}
var response = await storageClient.createWriteStream(request);
writeStream = response[0].name
var serializedRows = []
//Row 1
student.setId(1)
student.setName('st1')
student.setAge(15)
serializedRows.push(student.serializeBinary())
//Row 2
student.setId(2)
student.setName('st2')
student.setAge(15)
serializedRows.push(student.serializeBinary())
var protoRows = {
serializedRows
}
var proto_data = {
writerSchema: {protoDescriptor},
rows: protoRows
}
// Construct request
request = {
writeStream,
protoRows: proto_data
};
// Insert rows
const stream = await storageClient.appendRows();
stream.on('data', response => {
console.log(response);
});
stream.on('error', err => {
throw err;
});
stream.on('end', async () => {
/* API call completed */
try {
var response = await storageClient.finalizeWriteStream({name: writeStream})
response = await storageClient.batchCommitWriteStreams({parent,writeStreams: [writeStream]})
}
catch(err) {
console.log(err)
}
});
stream.write(request);
stream.end();
}
catch(err) {
console.log(err)
}
}
run();
Make sure your environment variables are set correctly to point to the file containing google cloud credentials.
Change project and dataset values accordingly.

SQLite3 Database is not a constructor

So in my project I am trying to gather simple Discord username and unique identifier from discord and store it in SQLite database file. I get the error:
` let userDB = new sqlite.Database('./disco.db', sqlite.OPEN_READWRITE);
^
TypeError: sqlite.Database is not a constructor`
Here is my code in my index.js
// Requirements
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require('fs');
const ServList = client.guilds.cache.size;
const sqlite = require('sqlite3').verbose();
require('dotenv').config()
//client login function
client.login(process.env.TOKEN);
// Start up Check list
client.once('ready', () => {
//Log and Set Status
console.log('Bot Online');
client.user.setActivity(`Proudly in ${client.guilds.cache.size} servers`, {
type: "WATCHING",
}, 60000);
//Database Initialization
let userDB = new sqlite.Database('./disco.db', sqlite.OPEN_READWRITE | sqlite.OPEN_CREATE);
});
Here is my code for the command that is creating the error:
const Discord = require('discord.js');
const sqlite = require('sqlite3').verbose();
module.exports = {
name: 'create',
description: "Create your account!",
use(message, args, client, sqlite){
// Data to Add
let userDB = new sqlite.Database('./disco.db', sqlite.OPEN_READWRITE);
userDB.run(`CREATE TABLE IF NOT EXIST usersInfo(userID INTEGER NOT NULL, uNameR TEXT NOT NULL)`);
let userID = message.author.id;
let uName = message.author.tag;
let uQuery = `SELECT * FROM usersInfo WHERE userID = ?`;
userDB.get(uQuery, [userID], (err, row) => {
if (err) {
console.log(err);
return;
}
if (row === undefined){
userDB.prepare(`INSERT INTO usersInfo VALUES(?,?)`);
insertdata.run('userID, uName');
insertdata.finalize();
userDB.close();
} else {
let userID2 = row.userID;
let yName = row.uNameR;
console.log(yName, userID);
}
});
message.channel.send('success');
}
}
Edit: Your question has been identified as a possible duplicate of another question. If the answers there do not address your problem, please edit to explain in detail the parts of your question that are unique.
The suggestion solution does not work for me as the suggested answer utilizes mySQL while I use SQLite3, Not only that but the suggested answer attempts to connect to a hosted database while mine is local.

How do I add attendees to a Calendar Event for the first time?

I have followed the answer here, which was really helpful:
How do I send the standard invitation email when calling addGuest on a CalendarEvent?
However, when I create an event in Apps Script it doesn't have an attendees property to add the email address to.
If I add a person to the invite manually, and then run the code, it executes successfully because there is now an attendee property to update.
Code to create the event:
function createCalendarEntry(programmeCalendar, eventName, eventStartDateTime, eventEndDateTime) {
var programmeCalendarID = CalendarApp.getCalendarById(programmeCalendar);
var event = programmeCalendarID.createEvent(eventName,
new Date(eventStartDateTime),
new Date(eventEndDateTime),
{sendInvites:true});
console.log('Event ID: ' + event.getId());
//Stop guests inviting other people
event.setGuestsCanInviteOthers(false);
var eventID = event.getId();
return eventID;
}
Code to add a new guest:
// Invite the user to the given event using the Advanced Calendar API
var trimmedEventID = eventID.toString().replace('#google.com', '');
var programmeCalendarID = 'my-calendar#example.com';
var advancedEvent = Calendar.Events.get(programmeCalendarID, trimmedEventID);
console.log('Advanced Event:' + advancedEvent);
if (typeof advancedEvent.attendees === 'undefined') {
console.log('Advanced Event Attendees: is undefined');
// how can I add the attendee property here?
} else {
var attendees = advancedEvent.attendees;
console.log('Advanced Event Attendees: is defined' + attendees);
attendees.push({email: guestEmailAddress});
var resource = { attendees: attendees };
}
var args = { sendUpdates: "all" };
// Add the guest to the invite while also sending an invite email
var eventObjectForDebugging = Calendar.Events.patch(resource, programmeCalendarID, trimmedEventID, args);
console.log('Event object for debugging:' + eventObjectForDebugging);
As you can read in the documentation, you can add guests with the option object, which has the following parameters:
You are actually already using this object in your code:
{sendInvites:true});
So adding the field guests to your object will be enough to add attendees:
{guests:'test1#example.com, test2#example.com', sendInvites:true});
It looks like you don't want to add guests to the event at the time of creation. Therefore you will end up with an event without an attendees[] property in the Event resource.
When you do come to add an attendee, you can do it like this:
// Invite user to the given event using the Advanced Calendar API
var trimmedEventID = eventID.toString().replace('#google.com', '');
var programmeCalendarID = 'my-calendar#example.com';
var advancedEvent = Calendar.Events.get(programmeCalendarID, trimmedEventID);
console.log('Advanced Event:' + advancedEvent);
var attendees = advancedEvent.attendees;
if (attendees) {
// If there are already attendees, push the new attendee onto the list
attendees.push({email: guestEmailAddress});
var resource = { attendees: attendees };
} else {
// If attendees[] doesn't exist, add it manually (there's probably a better way of doing this)
var resource = { attendees: [{email: guestEmailAddress}] }
}
var args = { sendUpdates: "all" };
var eventObjectForDebugging = Calendar.Events.patch(resource, programmeCalendarID, trimmedEventID, args);
console.log('Event object for debugging:' + eventObjectForDebugging);

Updating a value in SQL (better-sqlite3) with Node.JS

I currently have a database of people with each individual person and they hold a status value. I am trying to change their status value.
const id = parseInt(req.params.id , 10);
const { valid, messageObj } = validateId(id);
if (!valid) {
res.status(400).send(messageObj);
}
let { status, priority } = req.body;
let people = db.prepare('select * from people').all();
const person = people.find(person => person.id === id);
if(status !== 'none' & status == 'ready' || status == 'done'){
let updates = db.query(
'UPDATE people SET ? WHERE ?',
[{ status: status }, { id: id }]
);
}
I keep getting an error of db.query is not a function but I get that for every function that I try.
Pretty new to SQL but just trying to figure this out or any documentation that will help me as the better-sqlite3 doesn't have any update functions in the official documentation.
I cannot find a function called query() in the better-sqlite3 API for the Database class. I think that you would need to prepare() a Statement object, then run() it.
Also, column names cannot be passed as bound parameters. Your query should look like:
UPDATE people SET status = ? WHERE name = ?
You would need to change this:
let updates =
db.query('UPDATE people SET ? WHERE ?', [{ status: status }, { id: id }]);
To:
const stmt = db.prepare('UPDATE people SET status = ? WHERE id = ?');
const updates = stmt.run(status, id);
According to templates you can use javascript syntax to replace variables to its value.
let updates = db.exec(`UPDATE people SET status='${status}' WHERE id='${id}'`);

function + module.exports

I have a problem with module.export on titanium. I tried following https://wiki.appcelerator.org/display/guides/CommonJS+Modules+in+Titanium but it doesn't work at all.
I have 2 little pieces of code. App.js:
var fenetreBase = Titanium.UI.createWindow({fullscreen:true,backgroundColor:"white",exitOnClose:true});
fenetreBase.open();
var vueimage = new (require('UI/viewimage'))();
vueimage.test();
fenetreBase.add(vueimage);
and viewimage.js in the folder UI.
function viewimage() {
var lavue = Ti.UI.createView({backgroundColor:'red' });
var item =...
lavue.add(item...);
return lavue;
}
viewimage.prototype.test = function() {
Ti.API.info("test");
};
module.exports = viewimage;
I have an error saying
Object #<view> has no method 'test' in app.js vueimage.test()
In my mind, I follow the example of "Instantiable Objects" in the wiki above but I may have not understand something. I expect I made a stupid mistake. I tried many other things, each uglier than other and it doesn't work anyway.
Can somebody tell me where the mistake is?
your mistake is assuming that you have an instance of viewimage when you run:
var vueimage = new (require('UI/viewimage'))();
you are getting an instance of
var lavue = Ti.UI.createView({backgroundColor:'red' });
which doesn't have a test property.
Perhaps you could use an object like this instead:
function viewimage() {
var result = {};
var lavue = Ti.UI.createView({backgroundColor:'red' });
var item =...
lavue.add(item...);
result.lavue = lavue;
result.test = function() {
Ti.API.info("test");
};
return result;
}
EDIT
In your App.js:
var vueimage = new (require('UI/viewimage'))();
vueimage.test();
fenetreBase.add(vueimage.lavue);