To learn a little bit how a back end application works i'm currently creating a small instagram-like app using nodejs and sequelize (reactjs for the front).
I have 3 SQL tables :
Users
id (pk)
username
email
password
Posts
id (pk)
userId (fk)
message
mediaUrl
Following
id (pk)
userId (fk)
followingId (fk)
I would like to know what is the cleanest way to retrieve posts from an array of followingId corresponding to a userId ?
I just found a way to achieve what i wanted :
const db = require("../models");
const User = db.users;
const Post = db.posts;
const Following = db.followers;
const Op = db.Sequelize.Op;
exports.requestPost = async (req, res) => {
const followers = await Following.findAll({
where: {
userId: req.body.userId
},
attributes: [
['followingId', 'followingId']
]
});
const result = await followers.map(x => x.followingId);
const posts = await Post.findAll({
where: {
userId: result
}
});
return res.send(posts)
}
Related
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.
Hello I'm trying to take data from a sql table but the data that I want to check is into an array, so I need compare the data to check if an user is into the group, the array only have the IDs from users and the specific ID that I want is being bringing to me through the login.
This code is in Typescript.
If you need more information let me know please.
class CompanyController {
async consultCompanys(req: Request, res: Response) {
let response: ResponseModel = new ResponseModel(ECodeResponse.Ok, "", []);
const { UserId } = req.body;
try {
const Companies: any = await pool.query(
`SELECT (CompanyId) From Companies Where Members = '${UserId}'`
);
response.Code = ECodeResponse.Ok;
response.Message = EWarningMessage.Error;
return res.json(response);
} catch (error) {
response.Code = ECodeResponse.Warning;
response.Message = EWarningMessage.Error;
return res.json(response);
}
}
}
I'm a litle oxidated in this kind of consults
I use react native through firebase database
I have a database creating products each product has a number
I want to take a number and compare it with the product number
And if there is then I want to get a product
the function its give me my correct name but where i use it on render its not found the variable (name)
getAllContact = async key => {
let barCodeData2 = this.props.navigation.state.params.barcodeData
let self = this;
let contactRef = firebase.database().ref()
contactRef.on("value", dataSnapsot => {
if (dataSnapsot.val()) {
let contactResult = Object.values(dataSnapsot.val())
let contactKey = Object.keys(dataSnapsot.val())
contactKey.forEach((value, key) => {
contactResult[key]["key"] = value
})
self.setState({
fname: contactResult.fname,
data: contactResult.sort((a, b) => {
var nameA = a.barcode
var nameB = barCodeData2
const name = a.fname
console.log(`${nameA} What numers issssssss`);
if (nameA == nameB) {
alert(`${name} ........`)
console.log(`${nameA == nameB}is Equqlqlqlql`);
return name
}
}),
})
}
})
}
render() {
let t=this.state.name
alert(`${t} how?`)// is give Not found
// let d = this.props.navigation.state.params.barcodeData
return (
)
}
When you try such a comparison query i.e.
let ref = firebase.firestore();
ref.collection('zoo')
.where("id", "==", myID)
.get()
.then((snapshot) => {
console.log(snap.empty); //this will denote if results are empty
snapshot.forEach(snap => {
console.log(snap.exists); //alternatively this will also tell you if it is empty
})
})
well what you can do is run query based on you product no and if there's a product you will a product if there's none you will get an empty array.
read firebase documentation on queries
https://firebase.google.com/docs/reference/js/firebase.database.Query
Anyone able to help me out on this code .. What i expect to happen is when i hit thie URL I want it to update the DB Table with the user_name that is passed in the URL
Example: A user goes to /update/michael then I expect it to update the surname to Bloggs where the user_name is michael
app.get("/update/:user_name", function(req , res){
var user_name = req.params.name;
sql.connect(config, function() {
const request = new sql.Request();
request.query("UPDATE table SET surname = 'Bloggs' WHERE user_name= + 'req.params.name'", (err, recordset) => {
res.end(JSON.stringify(recordset));
});
});
});
I updated the code please try this and let me know in comments if it's not work.
app.get("/update/:user_name", function(req , res){
var user_name = req.params.user_name;
sql.connect(config, function() {
const request = new sql.Request();
request.query("UPDATE table SET surname = 'Bloggs' WHERE user_name= '"+user_name+"'", (err, recordset) => {
res.end(JSON.stringify(recordset));
});
});
});
I am working on a project. I am using Angular 2 as a front end and firebase as backend. TO access the data from Firebase i am using express. I am using REST methodology. Now all i am facing an issue here is to rest the data after i delete anything or update anything in the List. I am posting Delete and Update code. Please let me know whether i am doing any mistake or what.
router.route('/contacts/:id').get(function(req , res) {
//Show contact based on ID which is passed as perameter
var contactId = req.params.id;
contactRef.child(contactId).once('value' , function(snapshot) {
if(snapshot.exists()) {
var contactVal = snapshot.val();
res.json(contactVal);
} else {
res.json({message : "Contact does not exist"});
}
})
}).delete(function(req,res) {
//Deletes the Contact based on the ID which we are passing as perameter
var contactId = req.params.id;
console.log(contactId);
contactRef.child(contactId).remove(function(){
console.log("deleted")
});
res.json({message : "Contact with contact id "+ contactId +" has been removed"});
}).put(function(req, res) {
//Updates the contact based on ID passed in the perameter.
var contactId = req.params.id;
console.log(req.body);
contactRef.child(contactId).update();
contactRef.child(contactId).once(req.body , function(snapshot) {
//
if(snapshot.exists()) {
console.log("Contact Id" + contactId)
var contactVal = snapshot.val();
res.json({"contact ID " : contactId} );
} else {
res.json({message : "Contact does not exist"});
}
})
})
This is the code i am using but not having any idea what to do. Please let me whether i am doing anything wrong then.