findAll() return [object SequelizeInstance:table name] (mysql) - mysql

my code is :
app.get('/main', function(req, res) {
Posts.findAll().then(function(posts){
res.render(__dirname + "/home.pug", {posts:posts});
})
at node and :
div
each val in posts
li= val
at pug, but it return:[object SequelizeInstance:mensages](mensages is the database name) instead the value
sorry for my English and if the question is confuse

Because you are trying to render the model instances of sequelize returned by Posts.findAll() method.
You maybe want to render a property of post, not the entire model instance object.
E.g.
app.ts:
import express from 'express';
import path from 'path';
import { DataTypes, Model } from 'sequelize';
import { sequelize } from '../../db';
class Posts extends Model {}
Posts.init(
{
name: DataTypes.STRING,
},
{ sequelize, tableName: 'posts' },
);
const app = express();
app.set('view engine', 'pug');
app.set('views', path.resolve(__dirname, './views'));
app.get('/', (req, res) => {
Posts.findAll().then(function(posts) {
res.render('home.pug', { posts: posts });
});
});
(async function main() {
await sequelize.sync({ force: true });
//seed
await Posts.bulkCreate([{ name: 'teresa' }, { name: 'teng' }]);
app.listen(3000, () => console.log('Server started at http://localhost:3000'));
})();
views/home.pug:
<!DOCTYPE html>
html(lang="en")
head
meta(charset="UTF-8")
meta(name="viewport", content="width=device-width, initial-scale=1.0")
title Document
body
div
each val in posts
li= val.name
HTML output:
source code: https://github.com/mrdulin/node-sequelize-examples/tree/master/src/examples/stackoverflow/65376890

Related

cannot get/ posts error on localhost:5000/posts (I tried router .get ('/posts', getPosts); but didn't resolved

Here is my server side of folder routes/ post.js file
//server/routes/post.js
import express from 'express';
import {getPosts, createPost} from
'../controllers/posts.js'
const router = express.Router();
router.get('/' , getPosts);
router.get ('/posts', getPosts);
router.post('/' ,createPost);
export default router;
Here is my server folder of controllers/file posts.js file
//server/controllers/posts.js
import PostMessage from '../models/postMessage.js';
export const getPosts = async(req, res) => {
try {
const postMessages = await PostMessage.find();
res.status(200).json(postMessages);
} catch (error) {
res.status(404).json({message: error.message});
}
}
export const createPost = (req, res) => {
res.send('Post Creation');
}
Here is my server in which folder models/file postMessage.js postMessage.js code;
server/models/postMessage.js
import mongoose from 'mongoose';
const postSchema = mongoose.Schema({
title: String,
message: String,
creator: String,
tags: [String],
selectedFile: String,
likeCount: {
type: Number,
default: 0
},
createdAt : {
type: Date,
default: new Date()
},
});
const PostMessage = mongoose.model ('PostMessage',
postSchema);
export default PostMessage;

Sequelize belongs to many get and post request

I have belongs to many associations of the model Technology and Project. At the same time, on the client, I have two tables, free technologies and technologies on the project. Please tell me (or suggest how to do it) how to make a get request for all free technologies and a post request to add them to the table on the project. I figured out all the associations, but stopped at this one. I will be grateful for any help.
models/Project.js
const {
Model
} = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class Project extends Model {
static associate(models) {
Project.hasMany(models.Role, { foreignKey: "projectId", as: "roles" });
Project.belongsToMany(models.Technology, { foreignKey: "projectId", through: "ProjectsTechnologies"});
}
};
Project.init({
title: DataTypes.STRING,
description: DataTypes.STRING,
image: DataTypes.STRING
}, {
sequelize,
modelName: "Project",
});
return Project;
};
models/Technology.js
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Technology extends Model {
static associate(models) {
Technology.belongsToMany(models.Project, { foreignKey: "technologyId", through: "ProjectsTechnologies"});
}
}
Technology.init({
name: DataTypes.STRING
}, {
sequelize,
modelName: 'Technology',
});
return Technology;
};
*models/ProjectsTechs
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class ProjectsTechnologies extends Model {
static associate(models) {
ProjectsTechnologies.belongsTo(models.Project, {foreignKey: "projectId"});
ProjectsTechnologies.belongsTo(models.Technology, {foreignKey: "technologyId"});
}
};
ProjectsTechnologies.init({
projectId: DataTypes.STRING,
technologyId: DataTypes.STRING
}, {
sequelize,
modelName: 'ProjectsTechnologies',
});
return ProjectsTechnologies;
};
Currently I'm doing this get request for get all free technologies
router.get("/techologies", async (req, res) => {
const listOfTech = await Technology.findAll({
include: [
{
model: Project,
as: "projects",
through: {
model: ProjectsTechnologies
}
}
]
});
res.json(listOfTech);
});
And post req for posting technologies in "On project" table
router.post("/create/:id", async (req, res) => {
const technology = await ProjectsTechnologies.create(req.body);
const project = await Project.findOne({
where: {
id: req.params.id
}
});
res.json(technology);
});
I also keep trying to do it differently, because these options don't seem right to me.
To query a list of technologies that are not used in any of projects you need to use a subquery in where option:
const listOfTech = await Technology.findAll({
where: Sequelize.literal('NOT EXISTS (SELECT 1 FROM `ProjectsTechnologies` where `ProjectsTechnologies`.`technologyId`=`Technology`.`id`)')
});

How do I fetch just one object from the mySQL database?

I want to get and res.send user_image from the table. I tried to use attributes: ['user_image'], but it does not work. Is there any other keyword or style to fetch just one object?
const router = require('express').Router();
const db = require('../models');
router.get('/image/:user_id', (req, res) => {
try {
db.Customer.findAll({
where: {
user_id: req.params.user_id,
attributes: ['user_image'],
},
}).then((user) => res.send(user));
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;

Vue CRUD using NodeJs (MySql conncetion) - How do I get the data from server-side to client-side?

I'm trying to learn more about Vue and to make it interesting I have connected to my MySql-DB using nodeJS.
By following a tutorial (https://webdeasy.de/en/complete-login-system-with-node-js-vue-js-restapi-jwt-part-1-2/) I have a working Login system. Now I want to fetch some data from another table (the table called 'clients') and make a simple CRUD, but I do not understand how to get the data from the Server-side(node-js) to the Client-side(Vue).
I got a connection working where I can output my table data in the console.log - And I know I have use Axios (pointing to localhost:3000 where my server is running) to make it work, but everything I have tried either crashes my app or just doesn't work.
My router.js filer (Server-side) looks like this (I didn't paste all the login 'stuff' to keep clean for you):
// routes/router.js
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const uuid = require('uuid');
const jwt = require('jsonwebtoken');
const db = require('../lib/db.js');
const userMiddleware = require('../middleware/users.js');
// All the login code is here
// All the login code is here
// All the login code is here
db.query
("SELECT * FROM clients", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
module.exports = router;
Which correctly returns this in the console.log:
[nodemon] starting `node Server`
The server running on port 3000
[
RowDataPacket {
id: 1,
name: 'Sample Client One',
email: 'email-one#domain.com',
phone: '12345678'
},
RowDataPacket {
id: 3,
name: 'Sample Client two',
email: 'mail-two#domain.com',
phone: '12345678'
}
My Clients.vue looks like this now:
<template>
<div>
<h1>Hi {{ username }}, Welcome to Clients</h1>
<p>{{ secretMessage }}</p>
</div>
</template>
<script>
import AuthService from '#/services/AuthService.js';
export default {
data() {
return {
secretMessage: 'Sample secret message',
username: '',
};
},
async created() {
if (!this.$store.getters.isLoggedIn) {
this.$router.push('/login');
}
this.username = this.$store.getters.getUser.username;
this.secretMessage = await AuthService.getSecretContent();
},
methods: {
logout() {
this.$store.dispatch('logout');
this.$router.push('/login');
}
}
};
</script>
I have Axios installed, I just removed the import of it to avoid the error.
As you probably can see a am new at this so let me know if going about this all wrong or if you need to see more of my code.
//Rue
Make sure that you are fetching the clients from an CRUD endpoint.
For instance, you can add a new /clients endpoint where you read all the clients then return them back to client-side with res.status(200).send(result), as follows:
router.get('/clients', (req, res, next) => {
db.query("SELECT * FROM clients", function (err, result, fields) {
if (err) {
res.status(400).send();
throw err;
};
console.log(result);
res.status(200).send(result);
});
});
And your client-side code now needs to fetch data from server-side. One can create a new file ClientServices.js under services/ folder, like so
// src/services/ClientServices.js
import axios from 'axios';
const url = 'http://localhost:3000/api/';
export default {
getClients() {
return axios
.get(url + 'clients/')
.then(response => response.data);
}
};
The UI code now needs to import the new file and call getClients method and list them.
<template>
<div>
<h1>Hi {{ username }}, Welcome to Clients</h1>
<p>{{ secretMessage }}</p>
</div>
<div :key="client.id" v-for="client in clients">
<strong>client.name</strong>
<small>client.email</small> | <small>client.phone</small>
</div>
</template>
<script>
import AuthService from '#/services/AuthService.js';
import ClientService from '#/services/ClientService.js';
export default {
data() {
return {
secretMessage: 'Sample secret message',
username: '',
clients: [],
};
},
async created() {
if (!this.$store.getters.isLoggedIn) {
this.$router.push('/login');
}
this.username = this.$store.getters.getUser.username;
this.secretMessage = await AuthService.getSecretContent();
var self = this
ClientService.getClients().then((clients) => {
self.clients = clients;
});
},
methods: {
logout() {
this.$store.dispatch('logout');
this.$router.push('/login');
}
}
};
</script>

How to make a PUT request to an Express application

I'm trying to create a web application using Angular and Node for study, but my PUT request isn't working even though my GET requests work. It seems like Node is ignoring the requests and I can't find why. In my app I try to edit the name of a user when clicking a button and I can see that the request works until it gets to the http client in users-service.service.ts.
users.component.html
<router-outlet></router-outlet>
<h3>Usuários</h3>
<table>
<tr><td>Nome</td></tr>
<tr *ngFor="let user of users"><td>{{user.first_name}}</td><td><button (click)="showUserInfo($event, user)">Editar</button></td></tr>
</table>
<br/><br/>
<div>
<label>First Name: </label><input type="text" value="{{user.first_name}}" (input)="user.first_name = $event.target.value">
<label>Last Name: </label><input type="text" value="{{user.last_name}}" (input)="user.last_name= $event.target.value">
<button (click)="updateUser()">Salvar</button>
</div>
<br/><br/>
<button (click)="loadAllUsers()">Reload</button>
users.component.ts
import { HttpClient, HttpClientModule } from '#angular/common/http';
import { UsersService, User } from './../users-service.service';
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-users',
providers: [UsersService, HttpClient, HttpClientModule],
templateUrl: './users.component.html',
styleUrls: ['./users.component.sass']
})
export class UsersComponent implements OnInit {
private users: User[];
private user: User = {first_name: '', last_name: '', id: null};
constructor(private service: UsersService) {
this.loadAllUsers();
}
ngOnInit() {}
showUserInfo(event, u : User) {
this.user = u;
}
loadAllUsers() {
this.service.getAllUsers().subscribe(valor => { this.users = valor as User[] });
}
updateUser() {
console.log(this.user);
this.service.updateUser(this.user);
}
}
users-service.service.ts
import { HttpClient, HttpClientModule, HttpHeaders } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
export interface User{
first_name: string,
last_name: string,
id: number
}
#Injectable()
export class UsersService{
constructor(private http: HttpClient) { }
getAllUsers(): Observable<User[]>{
return this.http.get<User[]>("http://localhost:4600/api/users");
}
updateUser(user: User): Observable<void>{
console.log('Updating: ' + user);
console.log("http://localhost:4600/api/users/" + user.id);
return this.http.put<void>("http://localhost:4600/api/users/" + user.id, user);
}
}
server.js
const express = require('express');
app = new express();
const morgan = require('morgan');
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use('*', cors());
app.listen(4600, () => {
console.log("Server listening on port 4600...");
});
//All users
app.get("/api/users", (req, res) => {
let connection = getConnection();
connection.query('SELECT * FROM USERS', (err, result) => {
if(err){
throw err;
}
console.log(result);
res.json(result);
});
});
//Specific user
app.get('/api/users/:id', (req, res) => {
getConnection().query('SELECT * FROM USERS WHERE ID = ?', req.params.id, (err, result) => {
if(err){
console.log(err.message);
throw err;
}
res.json(result);
});
});
//Update user
app.put("/api/users/:id", (req, res) => {
console.log('PUT request received...');
getConnection().query("UPDATE USERS SET FIRST_NAME = ?, LAST_NAME = ? WHERE ID = ?", [req.body.first_name, req.body.last_name, req.body.id], (err, result) => {
if(err){
console.log(err.message);
throw err;
}
res.send(201, req.body);
});
});
//Delete user
app.delete('/api/users/:id', (req, res) => {
});
function getConnection(){
return mysql.createConnection({
host: 'localhost',
user: '',
password: '',
database: 'test'
});
}
EDIT 1
Based on #tadman comment I searched for the Network tools available in my browser and I found out, as expected, that the POST request were being ignored. By subscribing to the http client, the POST requests started to be noticed as they should. The answer by #KeaganFouche in the question bellow helped me:
Angular 4.0 http put request
New update method in the Angular service:
updateUser(user: User): void{
console.log('Updating: ' + user);
console.log("http://localhost:4600/api/users/" + user.id);
this.http.put<void>("http://localhost:4600/api/users/" + user.id, user).subscribe((response) => {console.log(response)});
}
Based on #tadman comment I searched for the Network tools available in my browser and I found out, as expected, that the POST request were being ignored. By subscribing to the http client, the POST requests started to be noticed as they should. The answer by #KeaganFouche in the question bellow helped me: Angular 4.0 http put request
New update method in the Angular service:
updateUser(user: User): void{
console.log('Updating: ' + user);
console.log("http://localhost:4600/api/users/" + user.id);
this.http.put<void>("http://localhost:4600/api/users/" + user.id, user).subscribe((response) => {console.log(response)});
}