I'm trying to implementing caminteJs on nodejs application, after define database schema on separated file i can't use that and i get this error:
TypeError: models.channels.create is not a constructor
i created models folder and in that i have some database schema which wrapped into separated file as
user.js //contains user table schema
news.js //contains news table schema
into index.js which its into models folder i have:
var users = require( './user' );
var news = require( './news' );
module.exports = {
users:users,
news:news
};
user.js file content:
var config = require('../config');
module.exports = function(schema){
var users = config.define('users', {
user_name: { type: schema.String, limit: 30 },
...
created_at: { type: schema.Date },
updated_at: { type: schema.Date }
});
return users;
};
config.js file content:
var caminte = require( 'caminte' ),
Schema = caminte.Schema,
config = {
driver: "mysql",
host: "localhost",
port: "3306",
username: "root",
password: "",
database: "test",
pool: true
},
schema = new Schema( config.driver, config );
module.exports = {
caminte: caminte,
Schema: Schema,
config: config,
schema: schema
}
and then my server.js to use them:
var socket = require( 'socket.io' ),
...
config = require( './config' ),
models = require( './models' );
io.on( 'connection', function (socket) {
socket.on( "new_user", function (data, device) {
const channels = new models.users.create(function(err){
user_name: 'Peter'
});
console.log( channels );
} );
} );
Depending on what you want and how your schema looks like but for creation try to use:
const user = models.users.create(function(err){
console.log('Error happened', err);
});
Related
I am using Express.js with sequelize
I am trying to get data from table but findALL() method not working
Here , I am sharing my models & controller file
checkout_product model
module.exports = function (sequelize, DataTypes) {
var Checkout_product = sequelize.define(
"Checkout_products",
{
name: {
type: DataTypes.STRING
},
ptice: {
type: DataTypes.STRING
},
image: {
type: DataTypes.STRING
},
quantity: {
type: DataTypes.INTEGER
},
},
);
Checkout_product.associate = function (models) {
Checkout_product.hasMany(models.Product_attribute, {
foreignKey: "product_id",
sourceKey: "id"
});
};
return Checkout_product;
};
product_attribute model
module.exports = function (sequelize, DataTypes) {
var Product_attribute = sequelize.define(
"product_attributes",
{
product_id: {
type: DataTypes.INTEGER
},
attribute_name: {
type: DataTypes.STRING
},
attribute: {
type: DataTypes.STRING
},
price: {
type: DataTypes.STRING
},
},
);
Product_attribute.associate = (models) => {
Product_attribute.belongsTo(models.Checkout_product, {
foreignKey: "product_id",
sourceKey: "id"
});
};
return Product_attribute;
};
models/index.js file
"use strict";
const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const config = require("./../config/development").database;
let sequelize = new Sequelize(
config.database,
config.username,
config.password,
config
);
let db = {};
fs
.readdirSync(__dirname)
.filter(function(file) {
return file.indexOf(".") !== 0 && file !== "index.js";
})
.forEach(function(file) {
let model = require(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
Controller
const Checkout_product = require('../models');
module.exports.checkout_product_get = function (req, res) {
Checkout_product.findAll({
include: [ {
model : Product_attributes,
}]
})
.then(checkout_product => {
res.json(checkout_product)
})
}
I am stuck to get data from checkout_product & it's child model product_attribute model,
Everytime I am getting same error : TypeError: Checkout_product.findAll is not a function
const Checkout_product = require('../models').table_name;
Can you try it
You are using the deprecated - legacy way of Sequelize to initialize models. Newer ways with require and extends are available and suggested. Check the docs for more information.
Regarding your code....
You are neither initializing the db structure properly nor using it correctly later...
First your code here in index.js:
.forEach(function(file) {
let model = require(path.join(__dirname, file));
db[model.name] = model;
});
Just loads the model files in the db object. But these files are functions ment to be called with sequelize object as parameter. This is done by providing them to sequelize.import that manages the proper call of the defined model-functions to create the model instances. Check https://sequelize.org/master/manual/models-definition.html
Also after successfully initializing the db, in your controller code, the require('../models') returns the total db object. So if you want to use a specific model as Checkout_product in your case, you have to access it in the object:
const db = require('../models');
db.Checkout_product.findAll()...
I am new to sequelize and I created a middleware called "db.js" with a connection to a mysql table called "users". Everytime, I attempt to run the app.js, I am getting this error: "TypeError: app.use() requires a middleware function".
However, I have a middleware function. See the code below: Am I missing something? I have the module.exports object at the end.
Should I have initialize sequelize?
db.js file
const Sequelize = require("sequelize");
const mysql = require("mysql");
const mysql2 = require("mysql2");
const db = {}
const sequelize = new Sequelize("smalldata", "root", "xxxx", {
host: "localhost",
dialect: "mysql",
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 90000
}
})
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db;
app.js file
const sequelize = require("sequelize");
const db = require("./middleware/db");
const express = require("express");
//Initialize Middleware
app.use(cors());
app.use(expressLayouts);
app.use(logger);
app.use(db);
user.js file
const Sequelize = require("sequelize");
const db = require("./db");
const User = db.sequelize.define(
'users',
{
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
}
},
{
timestamps: true
},
)
// Note: using `force: true` will drop the table if it already exists
User.sync({ force: true }).then(() => {
// Now the `users` table in the database corresponds to the model
definition
return User.create({
first_name: 'John',
last_name: 'Hancock',
email:'johnhancock#gmail.com',
password:'johnny'
});
});
module.exports = User
I found the error:
Capitalize error in app.js file:
const Sequelize = require("sequelize");
instead of:
const sequelize = require("sequelize");
I am working on a project with Javascript, Node,CSS,HTML and Google Maps.
I recently got this error => MissingSchemaError: Schema hasn't been registered for model "Marker". I ve tried everything I could to solve it but nothing seems to work.
This is the model for my markers:
const mongoose = require("mongoose");
const mongo = require("../connectors/mongo");
const Joi = require("Joi");
const markerSchema = new mongoose.Schema(
{
_id: String,
lat: { type: Number, required: true },
lng: { type: Number, required: true },
date: { type: Date, default: Date.now, required: false },
pictures: { type: [String], required: true },
user_id: { type: String, required: true }
},
{ timestamps: true }
);
/* Create the model from the schema. */
const Marker = mongoose.model("Marker", markerSchema);
exports.Marker = Marker;
For my routes I have a folder routes that has a folder markers and a folder for users.
The folder marker has these three things:
Folder users is similar.
handlers.js:
const Marker = require("mongoose").model("Marker");
const find = (req, res) => {
...
};
...
module.exports = {
create,
deletion,
find,
findById,
update
};
index.js:
const checkAuth = require("../../middlewares/check-auth.js");
const handlers = require("./handlers");
const validators = require("./validators");
module.exports = router => {
router.get("/markers", checkAuth, validators.find, handlers.find);
router.post("/markers", checkAuth, validators.create, handlers.create);
router.get("/markers/:id", checkAuth, validators.find, handlers.findById);
router.put("/markers/:id", checkAuth, validators.update, handlers.update);
router.delete(
"/markers/:id",
checkAuth,
validators.deletion,
handlers.deletion
);
return router;
};
and validators.js
const { celebrate, Joi } = require("celebrate");
const find = celebrate({
...
});
...
module.exports = {
find,
findOne,
create,
update,
deletion
};
The folder routes also has an index.js with this:
const markers = require("./markers");
const users = require("./users");
const resourceRoutes = [markers, users];
module.exports = router => {
resourceRoutes.forEach(routes => routes(router));
return router;
};
Any suggestions on what could be causing the problem?
In the last line on your model file, change to :
module.exports = Marker
Then at the beginning of your logic file, instead of const Marker = require("mongoose").model("Marker"); Just require the model file, like:
const Marker = require(PATH_TO_THE_MARKER_MODEL_FILE);
I'm new in node.
I'm trying to add Sequelize in my simple application with cosign.
config/db.js
var Sequelize = require('sequelize');
var sequelize = new Sequelize('test', 'root', '', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
}
});
module.exports = function () {
return sequelize
}
model/user.js
var Sequelize = require('sequelize');
module.exports = function(application, req, res){
var User = sequelize.define('user', {
username: {
type: Sequelize.STRING,
}
}, {
freezeTableName: true // Model tableName will be the same as the model name
});
User.create({ username: 'fnord'})
.then(function() {
console.log('criado!');
})
}
config/server.js
...
consign()
.include('app/routes')
.then('config/db.js')
.then('app/models')
.then('app/controllers')
.into(app);
module.exports = app;
I'm getting the error sequelize is not defined´ onvar User = sequelize.define('user', {`
What I'm doing wrong?
Create an index.js file inside your moldes folder like this:
"use strict";
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");
var sequelize = new Sequelize(global.config.dbConfig.name, global.config.dbConfig.user, global.config.dbConfig.password, {
host: global.config.dbConfig.host,
port: global.config.dbConfig.port,
pool: false
});
var db = {};
fs.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
module.exports = db;
and in your user.js do something like this:
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
username: {
type: DataTypes.STRING
},
{
freezeTableName: true // Model tableName will be the same as the model name
}
});
return User;
}
http://docs.sequelizejs.com/en/1.7.0/articles/express/
You should require sequelize instance into user model
config/db.js
module.exports = sequelize;
model/user.js
var Sequelize = require('sequelize');
var sequelize = require('../config/db.js'); //sequelize instance
module.exports = function(application, req, res){
var User = sequelize.define('user', {
...
The Sequelize-CLI is a very useful tool for projects that use Sequelize. When you download it
npm install -g sequelize-cli
You can then run
sequelize init
The above command will go and write out a few folders for you including a models folder that has the index file that Ricardo created above. This gives some really cool environment configuration as well. Within the new models folder, you can create a new file with your object with the syntax...
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
username: {
type: DataTypes.STRING
},
{
freezeTableName: true // Model tableName will be the same as the model name
}
});
return User;
}
While I do like this as a tool. It is key here to notice that Sequelize will go and look for the first argument to the define() method. So we could just write
module.exports = function(sequelize, DataType){
return sequelize.define("User", {
username: {
type: DataTypes.STRING
},
{
freezeTableName: true // Model tableName will be the same as the model name
}
});
I am trying to learn how to work with KrakenJs and use mysql for my database.
but I have not been able to find anything on line , this is what i have come up with so far
I have created a folder called lib and I want to have my connection file db.js to the database
'use strict';
var mysql = require('mysql');
var Sequelize = require('sequelize');
var sequelize = new Sequelize('site', 'root', 'root', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
},
});
module.exports = sequelize;
first of all I am not sure what needs to go my main index.js file config option part ...
'use strict';
var express = require('express');
var kraken = require('kraken-js');
var db = require('./lib/db');
var options, app;
/*
* Create and configure application. Also exports application instance for use by tests.
* See https://github.com/krakenjs/kraken-js#options for additional configuration options.
*/
options = {
onconfig: function (config, next) {
/*
* Add any additional config setup or overrides here. `config` is an initialized
* `confit` (https://github.com/krakenjs/confit/) configuration object.
*/
next(null, config);
}
};
How to set up my model , this is just a simple model , I just wanna get the idea of how to use it ...
'use strict';
var db = require('../lib/db');
module.exports = function User() {
var User = sequelize.define('user', {
firstName: {
type: Sequelize.STRING,
},
lastName: {
type: Sequelize.STRING
}
}, {
freezeTableName: true // Model tableName will be the same as the model name
});
};
and Lastly how to use it my controller
'use strict';
var User = require('../models/users');
module.exports = function (router) {
// var model = new User();
router.get('/', function (req, res) {
User.findOne().then(function (user) {
res.render('index', user);
});
});
};