Sequelize: cannot read property of undefined - javascript

I am experiencing an error using Sequelize and cannot figure out what the problem is.
I am creating a new record but after the record gets created it returns the results and then catches an exception and says the value is undefined. The record gets created but returns an error. I'm not sure why this is happening.
Here is my sql table
user_registration = conn.sequelize.define('user_registration',{
idUserRegistration:{
type: Sequelize.INTEGER(11).UNSIGNED,
primaryKey: true,
autoIncrement:true
},
email:{
type: Sequelize.STRING
},
firstName:{
type: Sequelize.STRING
},
lastName:{
type: Sequelize.STRING
},
guid:{
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV1
},
createDate:{
type: Sequelize.DATE, defaultValue: Sequelize.NOW
}
},{
freezeTableName: true
}
)
Here is the script for executing the statement
var
conn = require('../../mysql/mysqlConn')
,sequelize = require('sequelize')
,mysql = require('mysql')
,userRegistration = require('../../mysql/tables').user_registration
var createAccount = function(user,callback){
console.log('create user:',user.email)
var results = {}
try{
userRegistration.create({
email: user.email,
firstName: user.firstName,
lastName: user.lastName
})
.then(function(userRes){
console.log('userRegistration Results:',userRes)
results.error = false
results.results = userRes
callback(results)
})
.catch(function(err){
console.log('Caught error in createRegistration!')
console.log(err)
results.error = true
results.results = err
callback(results)
})
}catch(e){
console.log('EXCEPTION: error in createRegistration')
console.log(e)
results.error = true
results.results = 'Error occurred creating user registration:',e
callback(results)
}
}
exports.createAccount = createAccount
And here is the results with error that was encountered
create user: jsmith#me.com
Executing (default): INSERT INTO `user_registration` (`idUserRegistration`,`email`,`firstName`,`lastName`,`guid`,`create
Date`) VALUES (DEFAULT,'jsmith#me.com','John','Smith','a6193d70-198b-11e7-b0f0-93c15705c5db','2017-04-04 23:08:43');
userRegistration Results: Instance {
dataValues:
{ guid: 'a6193d70-198b-11e7-b0f0-93c15705c5db',
createDate: 2017-04-04T23:08:43.000Z,
idUserRegistration: 10,
email: 'jsmith#me.com',
firstName: 'John',
lastName: 'Smith' },
_previousDataValues:
{ email: 'jsmith#me.com',
firstName: 'John',
lastName: 'Smith',
idUserRegistration: 10,
guid: 'a6193d70-198b-11e7-b0f0-93c15705c5db',
createDate: 2017-04-04T23:08:43.000Z },
_changed:
{ email: false,
firstName: false,
lastName: false,
idUserRegistration: false,
guid: false,
createDate: false },
'$modelOptions':
{ timestamps: false,
instanceMethods: {},
classMethods: {},
validate: {},
freezeTableName: true,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: { email: 'jsmith#me.com' },
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks: {},
indexes: [],
name: { plural: 'user_registrations', singular: 'user_registration' },
omitNul: false,
sequelize:
Sequelize {
options: [Object],
config: [Object],
dialect: [Object],
models: [Object],
modelManager: [Object],
connectionManager: [Object],
importCache: {},
test: [Object],
queryInterface: [Object] },
uniqueKeys: {},
hasPrimaryKeys: true },
'$options':
{ isNewRecord: true,
'$schema': null,
'$schemaDelimiter': '',
attributes: undefined,
include: undefined,
raw: undefined,
silent: undefined },
hasPrimaryKeys: true,
__eagerlyLoadedAssociations: [],
isNewRecord: false }
Caught error in createRegistration!
TypeError: Cannot read property 'email' of undefined
Any ideas?

Related

MongoDB find() giving wrong object?

I am running a Mongo query from the Order database which aims to fetch the orders of a particular user by using his email. This is done using an API, but I am getting the complete object with some unnecessary details.
Code
I have written the following API in nextJS name myorders:
import Order from "../../models/Order";
import connectDB from "../../middleware/mongoose";
import jsonwebtoken from "jsonwebtoken";
const handler = async(req, res) => {
const token = req.body.token;
const data = jsonwebtoken.verify(token,process.env.JWT_SECRET);
console.log(data)
let mere_orders = Order.find({email: data.email})
console.log("mereorders12 = ", mere_orders)
res.status(200).json({mere_orders});
}
export default connectDB(handler);
And console.log("mereorders12 = ", mere_orders) gives me this:
mereorders12 = Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
_executionStack: null,
mongooseCollection: Collection {
collection: Collection { s: [Object] },
Promise: [Function: Promise],
modelName: 'Order',
_closed: false,
opts: {
autoIndex: true,
autoCreate: true,
schemaUserProvidedOptions: [Object],
capped: false,
Promise: [Function: Promise],
'$wasForceClosed': undefined
},
name: 'orders',
collectionName: 'orders',
conn: NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: {},
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype],
_readyState: 1,
_closeCalled: undefined,
_hasOpened: true,
plugins: [],
id: 0,
_queue: [],
_listening: false,
_connectionString: 'mongodb://localhost:27017/chesswear',
_connectionOptions: [Object],
client: [MongoClient],
'$initialConnection': [Promise],
db: [Db],
host: 'localhost',
port: 27017,
name: 'chesswear'
},
queue: [],
buffer: false,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { Order },
schema: Schema {
obj: {
email: [Object],
orderId: [Object],
paymentInfo: [Object],
products: [Object],
address: [Object],
subtotal: [Object],
status: [Object]
},
paths: {
email: [SchemaString],
orderId: [SchemaString],
paymentInfo: [SchemaString],
products: [Mixed],
address: [SchemaString],
subtotal: [SchemaNumber],
status: [SchemaString],
_id: [ObjectId],
updatedAt: [SchemaDate],
createdAt: [SchemaDate],
__v: [SchemaNumber]
},
aliases: {},
subpaths: {},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: { initializeTimestamps: [Function (anonymous)] },
methodOptions: {},
statics: {},
tree: {
email: [Object],
orderId: [Object],
paymentInfo: [Object],
products: [Object],
address: [Object],
subtotal: [Object],
status: [Object],
_id: [Object],
updatedAt: [Function: Date],
createdAt: [Object],
__v: [Function: Number],
id: [VirtualType]
},
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object] ],
'$id': 1,
mapPaths: [],
s: { hooks: [Kareem] },
_userProvidedOptions: { timestamps: true },
options: {
timestamps: true,
typeKey: 'type',
id: true,
_id: true,
validateBeforeSave: true,
read: null,
shardKey: null,
discriminatorKey: '__t',
autoIndex: null,
minimize: true,
optimisticConcurrency: false,
versionKey: '__v',
capped: false,
bufferCommands: true,
strictQuery: true,
strict: true,
pluralization: true
},
'$timestamps': { createdAt: 'createdAt', updatedAt: 'updatedAt' },
'$globalPluginsApplied': true,
_requiredpaths: [ 'status', 'subtotal', 'address', 'products', 'orderId', 'email' ]
},
op: 'find',
options: {},
_conditions: { email: 'mohit6#test.com' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection: NodeCollection {
collection: Collection {
collection: [Collection],
Promise: [Function: Promise],
modelName: 'Order',
_closed: false,
opts: [Object],
name: 'orders',
collectionName: 'orders',
conn: [NativeConnection],
queue: [],
buffer: false,
emitter: [EventEmitter]
},
collectionName: 'orders'
},
_traceFunction: undefined,
'$useProjection': true
}
But I should return order like this:
{
orders: [
{
"_id":"62693ae3f7fd0b7d87c8eb9c"},
"email":"mohit3#test.com",
"orderId":"1389629752594",
"paymentInfo":"No payment info",
"products":{...},
"address":"adasdklfasflka",
"subtotal":4,
"status":"Paid",
"createdAt":{"$date":"2022-04-27T12:45:23.352Z"},
"updatedAt":{"$date":"2022-04-27T12:45:23.352Z"},"__v":0
},
{
"_id":"62693ae3f7fd0b7d87c8eb9c"},
"email":"mohit3#test.com",
"orderId":"1389629752594",
"paymentInfo":"No payment info",
"products":{...},
"address":"adasdklfasflka",
"subtotal":14,
"status":"Paid",
"createdAt":{"$date":"2022-04-27T12:45:23.352Z"},
"updatedAt":{"$date":"2022-04-27T12:45:23.352Z"},"__v":0
}
]
}
Additionally this is the model schema of Order
const mongoose = require("mongoose");
const OrderSchema = new mongoose.Schema(
{
email: { type: String, required: true },
orderId: { type: String, required: true },
paymentInfo: { type: String, default: "No payment info" },
products: { type: Object, required: true },
address: { type: String, required: true },
subtotal: { type: Number, required: true },
status: { type: String, required: true, default: "Pending" },
},
{ timestamps: true }
);
export default mongoose.models.Order || mongoose.model("Order", OrderSchema);
Please help.
From Model.find(), it returns Query object.
Following the example, you need to execute the query asynchronously.
let mere_orders = await Order.find({email: data.email}).exec();
Or
let mere_orders = await Order.find({email: data.email});
As you are trying to return JSON as:
{
orders: [...]
}
You should return the response as below:
res.status(200).json({ orders: mere_orders });

Create a model with hash password in Sequelize?

I'm trying to create a model in Sequelize with a hash password using bcrypt, and run "sequelize db:migrate" but I can't. I get this error whenever I try to run it. All I need to is have "password" with the hash already done. I don't know where I'm going wrong or what I'm missing. can anybody help me?
== 001-user: migrating =======
ERROR: s.replace is not a function
I'm using: Sequelize: 6.16.2. Database: Postgres. Node: 15. Bcrypt: 5.0.1
Here is my User model:
class User extends Model {
/**
* #param {import("../index")} models
*/
static associate (models) {
User.belongsTo(models.UserRole, { as: "user_role", foreignKey: "id_user_role" });
}
}
/**
* #param {import("sequelize").Sequelize} sequelize Connection with the database
*/
function initUser (sequelize) {
User.init({
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
user: DataTypes.STRING(30),
name: DataTypes.STRING(100),
email: DataTypes.STRING(100),
password: DataTypes.STRING(100),
id_user_role: {
type: DataTypes.INTEGER,
references: {
model: sequelize.models.UserRole,
key: "id"
}
},
deleted: DataTypes.BOOLEAN
},
{
sequelize,
timestamps: false,
modelName: "User",
tableName: "user",
underscored: true,
hooks: {
beforeCreate: async (user) => {
if (user.password) {
const salt = await bcrypt.genSaltSync(11, "a");
user.password = bcrypt.hashSync(user.password, salt);
}
},
beforeUpdate: async (user) => {
if (user.password) {
const salt = await bcrypt.genSaltSync(11, "a");
user.password = bcrypt.hashSync(user.password, salt);
}
}
}
});
return User;
}
module.exports = { initUser };
User migration:
module.exports = {
/**
* #param {import("sequelize").QueryInterface} queryInterface
* #param {import("sequelize").DataTypes} Sequelize
*/
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable("user", {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
user: {
type: Sequelize.STRING(30),
allowNull: false
},
name: {
type: Sequelize.STRING(100),
allowNull: false
},
email: {
type: Sequelize.STRING(100),
allowNull: false
},
password: {
type: Sequelize.STRING(100),
allowNull: false
},
id_user_role: {
type: Sequelize.INTEGER,
allowNull: false,
references: { model: UserRole, key: "id" }
},
deleted: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
}
});
await queryInterface.bulkInsert("user", [
{
user: "admin", name: "test", email: "test#admin.com", password: "admin", id_user_role: 1
},
{
user: "comum", name: "test", email: "test#comum.com", password: "comum", id_user_role: 2
},
{
user: "regular", name: "test", email: "test#regular.com", password: "comum", id_user_role: 3
}
]);
}
};

How to get user-roles with sequelize?

I have a realtion like this:
in my resolver I am fetching the enteties like this:
users: async () => {
const users = await db.user.findAll({
include: [
{
model: db.userroles,
include: [
{
model: db.roles,
attributes: ['Name'],
},
],
},
],
});
I log what I get from the db:
console.log('users are', users[0].dataValues.userroles[0].dataValues.role.Name); // logs "users are developer"
Which shows me that the correct roles are fetched.
My graphql schema:
type user {
Id: ID!
Email: String
RoleId: Int!
Password: String
ChangedPassword: Boolean
WeddingId: Int!
AttendantId: Int
role: [roles!]
}
type roles {
Id: ID!
Name: String!
}
In the playground I am sending this:
{users
{role
{Name}}
}
result:
"data": {
"users": [
{
"role": null
}
]
}
}
When I log the entire user object that I get back from the db:
users are userroles {
dataValues:
{ UserId: 1,
RoleId: 1,
role:
roles {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false } },
_previousDataValues:
{ UserId: 1,
RoleId: 1,
role:
roles {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false } },
_changed: {},
_modelOptions:
{ timestamps: false,
validate: {},
freezeTableName: true,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: { plural: 'userroles', singular: 'userrole' },
omitNull: false,
tableName: 'userroles',
sequelize:
Sequelize {
options: [Object],
config: [Object],
dialect: [MysqlDialect],
queryInterface: [QueryInterface],
models: [Object],
modelManager: [ModelManager],
connectionManager: [ConnectionManager],
importCache: [Object] },
hooks: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: [ [Object] ],
includeNames: [ 'role' ],
includeMap: { role: [Object] },
includeValidated: true,
raw: true,
attributes: undefined },
isNewRecord: false,
role:
roles {
dataValues: { Name: 'Developer' },
_previousDataValues: { Name: 'Developer' },
_changed: {},
_modelOptions:
{ timestamps: false,
validate: {},
freezeTableName: true,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: [Object],
omitNull: false,
tableName: 'roles',
sequelize: [Sequelize],
hooks: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: undefined,
includeNames: undefined,
includeMap: undefined,
includeValidated: true,
raw: true,
attributes: [Array] },
isNewRecord: false } }
I am getting the roles I just can't figure out how to present them?
I think that the issue is in my resolver that I am missing yet another set of includes but I cant figure out how to write it.
user and roles have a many-to-many relationship with userRoles as the junction table. If you have not already, should should define this relationship on user:
user.belongsToMany(roles, { through: userRoles })
This will let you include roles directly:
const users = await db.user.findAll({
include: [
db.roles,
],
});
After posting I noticed some issues in my schema.
I changed my schema to:
type roles {
Id: ID!
Name: String!
}
type userroles {
RoleId: ID!
UserId: ID!
role: roles
}
type user {
Id: ID!
Email: String
RoleId: Int!
Password: String
ChangedPassword: Boolean
WeddingId: Int!
AttendantId: Int
userroles: [userroles!]
}
playground:
{users
{userroles
{role
{Name}}}
}
result:
"data": {
"users": [
{
"userroles": [
{
"role": {
"Name": "Developer"
}
}
]
}
]
}
}
The answer stared me right in the face but I was focused on the code in the resolver.
Leaving this question in case someone has another way of doing this.

Sequelize Seeding ARRAY(ENUM)

I cannot seem to figure out how to seed ARRAY(ENUM) using Sequelize. When I am registering a user via my app, I can create a new user fine, but when I am using the queryInterface.bulkInsert in a seed file, I am getting:
ERROR: column "roles" is of type "enum_Users_roles"[] but expression is of type text[]
here is my code:
return queryInterface.bulkInsert('Users', [
{
email: faker.internet.email(),
roles: ['user'],
password: "hash",
public_id: faker.random.uuid(),
created_at: new Date(),
updated_at: new Date()
}
]);
and here is my migration file for the user:
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
email: {
type: Sequelize.STRING,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
},
roles: {
type: Sequelize.ARRAY(Sequelize.ENUM({
values: ['user', 'setter', 'admin']
})),
allowNull: false
},
public_id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
allowNull: false
},
created_at: {
allowNull: false,
type: Sequelize.DATE
},
updated_at: {
allowNull: false,
type: Sequelize.DATE
}
})
I am just assuming that I am doing it wrong, but I cannot find any documentation on how to do it correctly. If anyone can help and explain (teach a man to fish), I would appreciate it.
Someone answered on github here
This is their answer which worked for me (and I greatly appreciate)
You can use this code
class Item extends Sequelize.Model { }
Item.init({
name: { type: DataTypes.STRING },
values: {
type: DataTypes.ARRAY(DataTypes.ENUM({
values: ['a', 'b']
}))
}
}, {
sequelize,
timestamps: true
})
sequelize.sync({ force: true }).then(async () => {
await sequelize.queryInterface.bulkInsert('Items', [
{
name: 'xyz',
values: sequelize.literal(`ARRAY['a']::"enum_Items_values"[]`),
createdAt: new Date(),
updatedAt: new Date()
}
]);
});
Executing (default): INSERT INTO "Items" ("name","values","createdAt","updatedAt") VAL
[1]: https://github.com/sequelize/sequelize/issues/11541#issuecomment-542791562
Obviously you'll want to change the array values and enum values. For example, mine would be
ARRAY['user']::"enum_Users_values"[]

Sequelize.define is not a function

I've recently started to play around with node.js so i am new to this. I'm getting the following error in my node.js console Can't upload images yet apparently because of my rating, please click the link
Below is my code.
var Sequelize = require('sequelize');
const dbConfig = new Sequelize('Mike_Test', 'sa', '[DBPASSWORD]', {
host:'179.27.69.555',
dialect: 'mssql',
port: 1433,
pool: {
max: 5,
min: 0,
idle: 10000
},
});
//Model Schhema
function createDB(){
var Customer2 = Sequelize.define('Customers2', {
Name: {
Name: Sequelize.STRING,
allowNull: false
},
Email: {
Email: Sequelize.STRING,
allowNull: false
},
Phone: {
Phone: Sequelize.STRING,
allowNull: false
},
Webiste: {
Webiste: Sequelize.STRING,
allowNull: true
},
Message: {
Message: Sequelize.STRING,
allowNull: true
},
createdAt: Sequelize.DATE,
updatedAt: Sequelize.DATE,
})
//Creates DB if it does not exist already.
Customer2.sync({force:true}).then(function() {
//Add to Cstomers2 Table
Customer2.create({Name: "Michael Sony", Email:
"michael#locationextreme.com", Phone: "01865657000", Website:
"https://www.youtbe.com", Message: "Blah Blah Blah!"})
});
};
createDB();
I have connected to a DB [Customers] with the above connection details successfully, but I can't create a new database and write to it [Customers2]
Changed code
var Sequelize = require('sequelize');
const dbConfig = new Sequelize('Mike_Test', 'sa', 'Georged0g', {
host:'172.27.60.139',
dialect: 'mssql',
port: 1433,
pool: {
max: 5,
min: 0,
idle: 10000
},
});
//Model Schhema
function createDB(){
var Customer2 = dbConfig.define('Customers2', {
Name: {
Name: Sequelize.STRING,
allowNull: false
},
Email: {
Email: Sequelize.STRING,
allowNull: false
},
Phone: {
Phone: Sequelize.STRING,
allowNull: false
},
Webiste: {
Webiste: Sequelize.STRING,
allowNull: true
},
Message: {
Message: Sequelize.STRING,
allowNull: true
},
createdAt: Sequelize.DATE,
updatedAt: Sequelize.DATE,
})
//Creates DB if it does not exist already.
Customer2.sync({force:true}).then(function() {
//Add to Cstomers2 Table
Customer2.create({Name: "Michael Sony", Email:
"michael#locationextreme.com", Phone: "01865657000", Website:
"https://www.youtbe.com", Message: "Blah Blah Blah!"})
});
};
createDB();

Categories