Message.Create is not a function sequelize cli - mysql

I have installed mysql sequelize in my project then I creadted Message Model using sequelize command which create model and migration file .I also given the db credentials in config.json file.Now I am trying to insert record in my db but getting this error here is my model file
DO i need to make db connection explicitly or it auto picks the
credential from config.json file to make connection ?
models/messages.js
'use strict';
module.exports = (sequelize, DataTypes) => {
var Messages = sequelize.define('Messages', {
room: DataTypes.STRING,
nickname: DataTypes.STRING,
message: DataTypes.STRING,
receiver: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
return Messages;
};
here is config.json file
config/config.json
{
"development": {
"username": "root",
"password": "asad",
"database": "chat",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
and here is my server file to save record
app.js file
var express = require('express');
var router = express.Router();
var app = express();
var server = require('http').createServer(app);
server.listen(4000);
var Messages=require('../models/Messages.js');
router.post('/', function(req, res, next) {
var a =req.body;
Messages.create(a).then(() => {
console.log('success ')
})
})

make sequelize connection instance and export it, please use config according to your environment
const sql = new Sequelize(config.database, config.username, config.password, {
host: config.host,
dialect: config.dialect,
pool: {
max: 5,
min: 0,
idle: 10000
},
});
module.export = sql;
In your app.js import sql instance and connect your db before starting your server.
var express = require('express');
var router = express.Router();
var app = express();
var server = require('http').createServer(app);
var sql = require(./sql);
sql.authenticate().then(()=>{
server.listen(4000);
});
var Messages= sql.import('../models/Messages.js');
router.post('/', function(req, res, next) {
var a =req.body;
Messages.create(a).then(() => {
console.log('success ')
})
})

Related

Unable to connect to mySQL from Node.js

I am able to connect via the mySQL shell, but when I try from VS Code Nodemon crashes and i get the error.
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlMessage: "Access denied for user 'root'#'localhost' (using password: YES)",
sqlState: '28000',
fatal: true
My environment variable path is set up.
I have run... ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY '123456'
I have set up a new user, granted them full permissions and tried to connect to that user but still denied access.
//server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
var mysql = require('mysql');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456'
});
db.connect((err) => {
if(err){
console.log(err);
} else {
console.log('Connected');
}
})
app.listen('8000', () => console.log("Server running on port 8000"));```
package.json
{
"name": "mern-prac-2-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"cors": "^2.8.5",
"express": "^4.18.2",
"mysql": "^2.18.1",
"nodemon": "^2.0.20"
}
}
Thanks!
(edited)
Based on Juans Answer I have changed to this...
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const {Sequelize} = require('sequelize');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const sequelize = new Sequelize('fake_company', 'root', '123456', {
host: 'localhost',
dialect: 'mysql',
});
const tryConnection = async () => {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
tryConnection();
app.listen('8000', () => console.log("Server running on port 8000"));
And am having the error ...
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlState: '28000',
sqlMessage: "Access denied for user 'root'#'localhost' (using password: YES)",
sql: undefined
I connect NodeJS con MySQL/MariaDB using sequelize package, this code is with typescript, you must change imports to require.
import { Sequelize } from 'sequelize';
// -----------------------------------------------------
const sequelize = new Sequelize('node', 'username', 'your-password', {
host: 'localhost',
dialect: 'mysql',
// logging: false
/* one of 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'db2' | 'snowflake' | 'oracle' */
});
// -----------------------------------------------------
export default sequelize;
//------------------------------------------------------
// Then in the server I have this code.
import express, { Application } from 'express';
import cors from "cors";
import userRoutes from '../routes/usuario.mjs';
import sequelize from '../db/connection.mjs';
class Server {
private app: Application;
private port: string;
private apiPath ={
usuarios: '/api/usuarios'
}
// -----------------------------------------------------
constructor(){
this.app = express();
this.port = process.env.PORT || '8000';
// connect to DB
this.dbConnection();
// ...
}
// -----------------------------------------------------
// Connect with DB
async dbConnection(){
try {
await sequelize.authenticate();
console.log('Database is connected.');
} catch (error: any) {
throw new Error( error.message );
}
}
}
It works porperly for my.
If you want to use sequelize, I think you can create the perfect configuration with sequelize init commands. Sequelize gives you a config file in a configuration folder like below. You have to define a database for sequelize don't forget that.
Firstly you have to install npm install --save-dev sequelize-cli for your cli commands.Then you can use sequelize init command.
{
"development": {
"username": "root",
"password": "123456",
"database": "your db",
"host": "127.0.0.1",
"dialect": "mysql",
"query": {
"raw": true
},
"options": {
"pool": {
"max": 5,
"min": 0,
"acquire": 30000,
"idle": 10000
}
}
},
{
"development": {
"username": "root",
"password": "123124",
"database": "yourDB",
"host": "127.0.0.1",
"dialect": "mysql",
"query": {
"raw": true
},
"options": {
"pool": {
"max": 5,
"min": 0,
"acquire": 30000,
"idle": 10000
}
}
},
I think creating a new user and giving it privilege will help. The root user might need root access or administrative access. And node doesn't have a root access.

I am not able to connect mysql database to reactjs .I am using nodejs for midddle ware

I made database called oldage_help. In mysql workbench. but i am not able to connect my database to React router by using nodejs as middleware
Database.js
const Sequelize = require("sequelize");
const databaseName = "oldage_help";
const databaseUserName = "root";
const databasePassword = "";
const databaseHost = "localhost";
const sequelize = new Sequelize(
databaseName,
databaseUserName,
databasePassword,
{
dialect: "mysql",
host: "localhost",
}
);
module.exports = sequelize;
app.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const sequelize = require("./helpers/database");
const User = require("./models/user");
const encryption = require("./helpers/encryption");
const authRoutes = require("./routes/user");
const PORT = 8000;
const app = express();
app.use(cors());
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(authRoutes);
sequelize
.sync() // This will run all the mgirations from the model and create tables in the database.
.then((result) => {
return User.findByPk(1);
})
.then(async (user) => {
if (!user) {
const ecryptedPassword = await encryption.encryptPassword("12345678");
return User.create({
firstName: "admin",
lastName: "admin",
email: "admin#help.com",
address: "some address line with street name in india",
city: "pune",
state: 1,
pincode: 411028,
password: ecryptedPassword,
});
}
return user;
})
.then((user) => {
app.listen(PORT);
})
.catch((err) => console.log(err));
user.js..\controllers
const encryption = require("../helpers/encryption");
const User = require("../models/user");
module.exports = {
register: async function (req, res, next) {
try {
console.log("req.body", req.body);
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const address = req.body.address;
const address2 = req.body.address2;
const city = req.body.city;
const state = req.body.state;
const pincode = req.body.pincode;
const password = req.body.password;
const ecryptedPassword = await encryption.encryptPassword(password);
const user = await User.create({
firstName: firstName,
lastName: lastName,
email: email,
address: address,
address2: address2,
city: city,
state: state,
pincode: pincode,
password: ecryptedPassword,
});
return user;
} catch (error) {
if (error.name == "SequelizeUniqueConstraintError") {
return {
error: true,
message: "email address already exists",
};
}
return {
error: true,
message: "something went wrong",
};
}
},
login: async function (req, res, next) {
try {
console.log("req.body", req.body);
const email = req.body.email;
const password = req.body.password;
const ecryptedPassword = await encryption.encryptPassword(password);
console.log("email. password", {
email: email,
password: ecryptedPassword,
});
const user = await User.findOne({
where: {
email: email,
},
});
if (user && user.id) {
const isPasswordMatch = await encryption.comparePassword(
password,
user.password
);
if (isPasswordMatch) {
return {
id: user.id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
address: user.address,
address2: user.address2,
city: user.city,
state: user.state,
pincode: user.pincode,
};
} else {
return {
error: true,
message: "invalid credentials, no user found with this credentials",
};
}
}
} catch (error) {
return {
error: true,
message: "invalid credentials, no user found with this credentials",
};
}
return {
error: true,
message: "invalid credentials, no user found with this credentials",
};
},
};
user.js../models
const Sequelize = require("sequelize");
const sequelize = require("../helpers/database");
const User = sequelize.define("users", {
id: {
type: Sequelize.BIGINT,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
firstName: {
type: Sequelize.STRING,
allowNull: false,
},
lastName: {
type: Sequelize.STRING,
allowNull: false,
},
email: {
type: Sequelize.STRING,
allowNull: false,
uniqueKey: true,
},
address: {
type: Sequelize.TEXT,
allowNull: false,
},
address2: {
type: Sequelize.TEXT,
allowNull: true,
},
city: {
type: Sequelize.TEXT,
allowNull: false,
},
state: {
type: Sequelize.TEXT,
allowNull: false,
},
pincode: {
type: Sequelize.TEXT,
allowNull: false,
},
password: {
type: Sequelize.TEXT,
allowNull: false,
},
});
module.exports = User;
Not giving such error msg but data is not going to database.I made web frontend through Reactjs and i want connect mysql to reactjs by use of nodejs as middleware.

error: SequelizeValidationError: string violation: created cannot be an array or an object

I am implementing MERN Stack Login / Registration and trying to test my response in Postman step by step. Firstly, I written the code for Registration then for Login but in case of calling registration link I am getting the following error in postman:
error: SequelizeValidationError: string violation: created cannot be an array or an object
Can someone provide any suggestions to help? I think in User.js findone() function is having some sort of miss from my side.
Could there be any other solution?
./database/DB.js
const db = {}
const sequelize = new Sequelize("mern", "root", "", {
host: "localhost",
dialect: "mysql",
port: "3307",
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
})
db.sequelize = sequelize
db.sequelize = sequelize
module.exports = db
./models/User.js
const db = require("../database/db")
module.exports = db.sequelize.define(
'user',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
first_name: {
type: Sequelize.STRING
},
last_name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
created: {
type: Sequelize.STRING
}
},
{
timestamps: false
}
);
./routes/User.js
const users = express.Router()
const cors = require('cors')
const jwt = require("jsonwebtoken")
const bcrypt = require('bcrypt')
const User = require("../models/User")
users.use(cors())
process.env.SECRET_KEY = 'secret'
users.post('/register', (req, res) => {
const today = new Date()
const userData = {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: req.body.password,
created: today
}
User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if(!user){
bcrypt.hash(req.body.password, 10, (err, hash) => {
userData.password = hash
User.create(userData)
.then(user => {
res.json({status: user.email + ' registered'})
})
.catch(err => {
res.send('error: ' + err)
})
})
} else {
res.json({error: "User already exists"})
}
})
.catch(err => {
res.send('error: ' + err)
})
})
users.post('/login', (req, res) => {
User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if(user) {
if(bcrypt.compareSync(req.body.password, user.password)) {
let token = jwt.sign(user.dataValues, process.env.SECRET_KEY, {
expiresin: 1440
})
res.send(token)
}
} else {
res.status(400).json({error: 'User does not exist'})
}
})
.catch(err => {
res.status(400).json({ error: err})
})
})
module.exports = users
package.json
"name": "login-registration",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^3.0.6",
"bcryptjs": "^2.4.3",
"body-parser": "^1.17.2",
"cors": "^2.8.4",
"express": "^4.16.3",
"jsonwebtoken": "^7.4.2",
"mysql": "^2.14.1",
"mysql2": "^1.6.1",
"nodemon": "^1.18.3",
"sequelize": "^4.38.0"
}
}
Server.js
var cors = require ('cors')
var bodyParser = require("body-parser")
var app = express()
var port = process.env.PORT || 5000
app.use(bodyParser.json())
app.use(cors())
app.use(bodyParser.urlencoded({extended: false}))
var Users = require('./routes/users')
app.use('/users', Users)
app.listen(port, () => {
console.log("Server is running at port: " + port)
})
In ./routes/User.js, under the /post register route, the userData object has a created field with today property which is a Date object.
In ./models/User.js you specify that created should have type Sequelize.STRING.
This is the contradiction that is causing the error. When you call User.create(userData), it gives you that error because the input parameter is of the wrong type.
To fix this, you either need to have created expect a type of Sequlize.Date or convert the today date object to a string.
const today = new Date().toJSON();
There are many different to string functions for the Date class. You should pick the one that best suits you here
This error is as a result of submitting a value of a wrong type compared to the
one declared in the model. Therefore, change it to the appropriate
type which is "JSON" instead of "STRING".
./models/User.js
const db = require("../database/db")
module.exports = db.sequelize.define(
'user',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
first_name: {
type: Sequelize.STRING
},
last_name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
created: {
type: Sequelize.JSON
}
},
{
timestamps: false
}
);
Its the "today" attribute that's causing the issue, you are trying to save a date obj instead of string. Change it to string while saving.

Sequelize throw AssertionErrors with MySQL

I'm building an API using nodejs, sequelize, dan MySQL database (10.1.21-MariaDB). When I tried to do some PATCHing (updating data), it throws AssertionErrors, but it works fine with POST (inserting data).
Here's my patch code:
const express = require('express');
const router = express.Router();
const brandModel = sequelize.define('tbl_brand', {
brand_name: {
type: Sequelize.STRING,
allowNull: false
},
}, {
freezeTableName: true,
});
router.patch('/:id', (req, res, next) => {
const id = req.params.id;
const newModel = {
brand_name: req.body.brand_name
};
sequelize.authenticate().then(() => {
const promise = brandModel.update(newModel, {brand_id: id});
return promise.then(function(item){
res.status(201).json({
success: true,
result: item
});
});
})
.catch(err => {
res.status(500).json({
success: false,
result: err
});
});
});
I use postman and access it like this:
http://localhost:3000/brand/1
With Raw JSON:
{
"brand_name" : "Adidasssss"
}
And here's the result:
{
"success": false,
"result": {
"generatedMessage": false,
"name": "AssertionError [ERR_ASSERTION]",
"code": "ERR_ASSERTION",
"expected": true,
"operator": "=="
}
}
What could be the problem?
Nevermind... I was careless, I was updating an empty instance called brandModel. It should be searched first then do the update

Insertion issue in Json Array object mongodb with Nodejs?

I am new to mongodb , I have below Json structure in mongodb ,
{
"_id" : ObjectId("59d62452a164b51d64b714c2"),
"folderName" : "Avinash 1234",
"tag" : "search",
"ismainFolder" : true,
"innerFolder" : [
{
"ismainFolder" : false,
"foldername" : "Test12",
"_id" : ObjectId("59d72246e66adf2cfcfdd6e6")
}
],
"innerFiles" : [
{
"filelocation" : "",
"isFolder" : false,
"filename" : "Penguins.jpg",
"_id" : ObjectId("59d7223de66adf2cfcfdd6e5")
},
{
"filelocation" : "",
"isFolder" : false,
"filename" : "Desert.jpg",
"_id" : ObjectId("59d72ff4e66adf2cfcfdd6ec")
},
{
"filelocation" : "",
"isFolder" : false,
"filename" : "Hydrangeas.jpg",
"_id" : ObjectId("59d731dfe66adf2cfcfdd6ed")
},
{
"filelocation" : "",
"isFolder" : false,
"filename" : "Chrysanthemum.jpg",
"_id" : ObjectId("59d73252e66adf2cfcfdd6ee")
}
],
"__v" : 0
}
For innerFiles array i need to insert the Tag field depending on the id ("_id" : ObjectId("59d7223de66adf2cfcfdd6e5")) . I used following nodeJs code but it adding as a new object . Please give me the solution .
exports.addTagForSearch = function (req, res, next) {
var tagDetails = req.body.tagDetails;
console.log("tagDetails", tagDetails);
console.log("tagDetails", tagDetails._id);
Repository.find({ _id: tagDetails._id, }, { innerFiles: { $elemMatch: { _id: tagDetails._id } } },function (err, response) {
$push: {
innerFiles: {
"tagName": tagDetails.tagname,
}
//"filelocation": tagDetails.filelocation
}
}, { upsert: true, new: true }, function (err, post) {
if (err) return next(err);
return res.status(200).json("success");
});
}
but above code inserting as a new object , Please give me solution please .
First I need to create a database for that I had a config.js file . Here is the code
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl' : 'mongodb://localhost:27017/innerFiles'
}
Next create a models folder and keep this order.js in it
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var folderSchema=new Schema({
ismainFolder:{
type:String,
//required:true,
default:''
},
foldername:{
type:String,
//required:true,
default:''
}
});
var innerSchema=new Schema({
filelocation:{
type:String,
//required:true,
default:''
},
isFolder:{
type:String,
//required:true,
default:''
},
filename:{
type:String,
//required:true,
default:''
}
});
var main= new Schema({
folderName:{type:String},
tag:{type:String},
ismainFolder:{type:String},
innerFolder:[folderSchema],
innerFiles:[innerSchema]
},{ strict: false });
var Order= mongoose.model('main', main);
// make this available to our Node applications
module.exports = Order;
Next create a routes folder and keep this orderRouter.js file in it
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Orders = require('../models/orders');
var app = express();
var orderRouter = express.Router();
orderRouter.use(bodyParser.json());
orderRouter.get('/get',function (req, res, next) {
Orders.find({}, function (err, order) {
if (err) throw err;
res.json(order);
});
})
orderRouter.post('/post',function (req, res, next) {
Orders.create(req.body, function (err, order) {
if (err) {
res.status(400).send('Bad request');
}
else{
console.log('order created!');
var id = order._id;
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Added the order with id: ' + id);
}
});
})
orderRouter.get('/:orderId',function (req, res, next) {
Orders.findById(req.params.orderId, function (err, order) {
if (err) {
res.status(404).send('OrderId not found');
}
else{
res.json(order);
}
});
})
orderRouter.put('/addingField',function(req,res){
//var tagDetails = req.body;
console.log("tagDetails:"+req.body.subId);
console.log("tagname:"+req.body.tagname);
Orders.update(
{_id:req.body.mainId,'innerFiles._id':req.body.subId},
{$set:{'innerFiles.$.tagName':req.body.tagname}},
function (err, article) {
if (err) return console.log(err);
res.json(article);
});
});
app.use('/orders',orderRouter);
app.use(express.static(__dirname+'/public'));
module.exports = orderRouter;
Next create a app.js file this is the server code
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log("Connected correctly to server");
});
var orderRouter = require('./routes/orderRouter');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// passport config
app.use(passport.initialize());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/orders',orderRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: {}
});
});
app.listen(3000,function(){
console.log("Server listening on 3000");
});
module.exports = app;
And run the server as node app.js.You can post data using this api http://localhost:3000/orders/post you need to use post method.Here is the sample input example for posting
{
"folderName" : "Avinash 1234",
"tag" : "search",
"ismainFolder" : "true",
"innerFolder" : [
{
"ismainFolder" : "false",
"foldername" : "Test12"
}
],
"innerFiles" : [
{
"filelocation" : "a",
"isFolder" : "false",
"filename" : "Penguins.jpg"
},
{
"filelocation" : "b",
"isFolder" : "false",
"filename" : "Desert.jpg"
},
{
"filelocation" : "c",
"isFolder" : "false",
"filename" : "Hydrangeas.jpg"
},
{
"filelocation" : "d",
"isFolder" : "false",
"filename" : "Chrysanthemum.jpg"
}
]
}
and here is the image for it
After posting data check that your data is stored in db or not.Here whatever the id I am giving in response is mainId . For that run this api http://localhost:3000/orders/get use get method for this. Collect the sub document id which is subId in our code.Sample Image for getting
After this here is the task of adding a new field to sub document for that use this api http://localhost:3000/orders/addingField and you need to use put method for this.Here is the input example
{
"mainId":"59dca6aff968a98478aaaa96",
"subId":"59dca6aff968a98478aaaa9a",
"tagname":"hello"
}
And Image for it
After completion of all these steps check into db.Here is the sample image for
it
That's it. Hope it helps.