I'm trying to create a database with a foreign key but I kept getting the error of no such column: created_at, even tho I'm not using created_at somewhere in my code. I wonder why and how to patch this issue.
var User = sequelize.define('user', {
username: Sequelize.STRING,
myhash: Sequelize.TEXT,
mysalt: Sequelize.STRING,
keyword: Sequelize.STRING,
})
, Company = sequelize.define('company', {
keyword: Sequelize.STRING
});
User.belongsTo(Company);
var User = sequelize.define('user', {
username: Sequelize.STRING,
myhash: Sequelize.TEXT,
mysalt: Sequelize.STRING,
keyword: Sequelize.STRING,
}, {underscored: true})
, Company = sequelize.define('company', {
uuid: {
type: Sequelize.UUID,
primaryKey: true
}
});
User.belongsTo(Company);
created_at is automatically created for keeping the timestamp. You need to set the timestamp option to false like below to all your model definitions.
var User = sequelize.define('user', {
username: Sequelize.STRING,
myhash: Sequelize.TEXT,
mysalt: Sequelize.STRING,
keyword: Sequelize.STRING,
},{
timestamps: false
})
Related
when I create a user in mongoose and I don't give my email, I get an error, but if I don't provide the password, nothing shows up and the user is saved to the database. in both cases I use: required: [true, "error "]
image
did you add validation for the password field? I do my user model like this:
const UserSchema = new Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
gender: {
type: String,
enum: ['male', 'female'],
},
profilePicture: {
type: String
},
password: {
type: String,
required: true,
},
email: {
type: String,
unique: true,
required: true,
},
}, {
timestamps: true
}, );
// hash the password before the user is saved
UserSchema.pre('save', function hashPassword(next) {
// hash the password only if the password has been changed or user is new
if (!this.isModified('password')) {
next();
return;
}
// generate the hash
_hash(this.password, null, null, (err, hash) => {
if (err) {
next(err);
return;
}
// change the password to the hashed version
this.password = hash;
next();
});
});
// method to compare a given password with the database hash
UserSchema.methods.comparePassword = function comparePassword(password) {
const data = compareSync(password, this.password);
return data;
};
I hope this helps :)
Have you tried adding minlength? Maybe trim would help?
https://mongoosejs.com/docs/schematypes.html#string-validators
email: {
type: String,
required: [true, 'Please provide an email.'],
minlength: 1,
maxlength: 25,
trim: true,
unique: true,
},
I set up the following tables and I use a many-to-many connection:
const Product = sequelize.define('Product',
{
name: DataTypes.STRING,
quantity: DataTypes.INTEGER
},
{ freezeTableName: true });
const Cart = sequelize.define('Cart',
{
customer_name: DataTypes.STRING,
total: DataTypes.FLOAT
});
const CartItem = sequelize.define('CartItem', {
selfGranted: DataTypes.BOOLEAN
},
{ timestamps: false });
Cart.belongsToMany(Product, { through: CartItem });
Product.belongsToMany(Cart, { through: CartItem });
And when I proceed to get the data, on the first request it sends me Relation doesn't exist error.
I forgot to remove the database re-sync.
db.sequelize.sync({ force: true }).then(() => {
console.log("Drop and re-sync db.");
});
I have 2 schema's, Categories and Cards. Each Category has an array of cards, and I want to populate that array with values , but I am unsure how to go about this as the mongoose documentation is somewhat confusing to understand.
// Schemas in seperate files
// Category Schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const categorySchema = new Schema({
title: {
type: String,
trim: true,
max: 30,
},
cards: [{ type: Schema.Types.ObjectId, ref: "categoryCard" }],
});
module.exports = mongoose.model("category", categorySchema);
// Category Card Schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const categoryCardSchema = new Schema({
category: {
type: String,
trim: true,
},
name: {
type: String,
trim: true,
},
post: {
type: String,
required: true,
trim: true,
},
});
module.exports = mongoose.model("categoryCard", categoryCardSchema);
// Below is the express router file . I want users to be able to create cards for different categories , after the category is already created. It worked in postman, but it doesn't work on the front end for some reason.
router.route("/createCard").post((req, res) => {
const { title, name, post } = req.body;
newCard = new categoryCard({
category: title,
name,
post,
});
newCard.save();
category.findOne({ title }).exec((err, item) => {
if (!err) {
item.cards.push(newCard._id);
item.save();
res.send(item);
} else {
res.send(err);
}
});
});
You can Follow this code...
let categorys= await category.findOne({ title }).populate("cards")
I have to connect to a Postgres database in Node.js and I want to switch schemas dynamically Using Sequelize Library.
Here is my Table Model and Controller Code.
module.exports = function (sequelize, DataTypes) {
const customer = sequelize.define(
'customer',
{
id: {
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
schema_name: {
type: DataTypes.STRING,
allowNull: false,
},
created_on: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW(),
},
},
{
schema: 'public',
}
)
return customer
}
And Controller Code
exports.login = async (req, res, next) => {
const { email, password, domain } = req.body
const domainData = await customer.findOne({
where: { schema_name: domain },
})
console.log('Log: exports.login -> domainData', domainData)
}
Once the response received I have to Switch Schemas Dynamically according to the above result.
Help me Guys Please
I resolved the problem using sequelize.query() function.
for getting Domain...
const domainData = await sequelize.query(
`SELECT schema_name from public.customer_management_client where schema_name = '${domain}'`
)
for switching to dynamic schema
const UserData = await sequelize.query(
`SELECT * from ${domainData[0][0].schema_name}.user_access_user where email = '${email}'`
)
I have been having SO much trouble trying to get a mutation to work.
Given this GraphQL Schema, can anyone PLEASE help me create a simple create User mutation? I don't understand what I am missing. I got it to a point where it throws a 400 error from the GraphQL server and it does not fire the resolve function.
var userType = new GraphQLObjectType({
name: 'User',
description: 'User creator',
fields: () => ({
id: {
type: new GraphQLNonNull(GraphQLString),
description: 'The id of the user.'
},
email: {
type: GraphQLString,
description: 'The email of the user.'
},
business: {
type: GraphQLString,
description:
'The name of the business of the user as the app refers to it.'
},
businessDisplayName: {
type: GraphQLString,
description: 'The name of the business of the user as they typed it in.'
},
trips: {
type: new GraphQLList(tripType),
description: 'The trips of the user, or an empty list if they have none.',
resolve: (user, params, source, fieldASTs) => {
var projections = infoToProjection(fieldASTs)
return Trip.find(
{
_id: {
// to make it easily testable
$in: user.trips.map(id => id.toString())
}
},
projections,
function(err, docs) {
return docs
}
)
}
}
})
})
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'root',
fields: {
trips: {
type: new GraphQLList(tripType),
resolve: function() {
return Trip.find({})
}
},
users: {
type: new GraphQLList(userType),
resolve: function() {
return User.find({})
}
},
user: {
type: userType,
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (root, { id }, source, fieldASTs) => {
return User.findOne(
{ _id: id },
infoToProjection(fieldASTs),
function(err, doc) {
return doc
}
)
}
},
trip: {
type: tripType,
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (root, { id }, source, fieldASTs) => {
var projections = infoToProjection(fieldASTs)
return Trip.findOne({ _id: id }, projections, function(err, doc) {
return doc
})
}
}
}
}),
// mutation
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: {
createUser: {
name: 'createUser',
type: userType,
args: {
input: { type: new GraphQLInputObjectType({
name: 'user',
fields: {
business: { type: GraphQLString },
email: { type: GraphQLString },
businessDisplayName: { type: GraphQLString }
}
})
}},
resolve: (parentValue, args) => {
let user = new User({ ...args.input })
user.save()
return user
}
}
})
})
export var getProjections = infoToProjection
export default schema
This works with GraphiQL using the following queries or mutations:
mutation {
createUser(input:{business:"business", email: "e#mai.l", businessDisplayName: "businessDN"}) {
id
email
business
businessDisplayName
}
}
fragment UserFragment on User {
id
business
businessDisplayName
trips{
title
}
}
{
hideya: user(id: "someid") {
...UserFragment
}
}
I finally fixed the problem. Tried to understand the source of the problem so I used a new NetworkLayer to enable appropriate logging and meaningful error messages. Then threw the an error when my mutation failed. The error message was : "Cannot query field clientMutationId". Looked that up and found that to be able to mutate objects you need to have that field on your GraphQL type. So I added it.
Lesson learned: I highly recommend using react-relay-network-layer.
More details:
Here is my code for it:
import {
RelayNetworkLayer,
urlMiddleware,
batchMiddleware,
} from 'react-relay-network-layer';
Relay.injectNetworkLayer(new RelayNetworkLayer([
batchMiddleware({
batchUrl: 'http://localhost:3000/graphql',
}),
urlMiddleware({
url: 'http://localhost:3000/graphql',
}),
]));
Note: This enables logging and by default it's a simple console.log.
Here is how I threw the error:
const params = {
email: email.toLowerCase(),
businessDisplayName: business,
business: business.toLowerCase()
}
var onSuccess = () => {
console.log('Mutation successful!')
}
var onFailure = transaction => {
var error = transaction.getError() || new Error('Mutation failed.')
console.error(error)
}
Relay.Store.commitUpdate(new FindOrCreateUser({ user: { ...params } }), { onFailure, onSuccess })
And of course you always need to clean your cache and restart your packager.