Console output in Mongoose promise not working - javascript

I am just working on an analysis project. I have a create method in node but I don't know why suddenly this is happening. I have connected to the database successfully. and wrote created a mongoose model successfully.Now in below code promise.then() is not visited. document is not created. but if I removed any required field, it throws a error as expected.
my create method:
create: function (doc) {
return new Promise((resolve, reject) => {
bcrypt.hash(doc.password, saltRounds).then((hash) => {
doc.password = hash;
console.log(doc); //works
Account.create(doc).then((account) => {
console.log(account); //not working, no error, successful execution, code exit 0.
resolve(account);
}).catch((err) => {
console.log(account); //nothing printed
reject(err);
});
}).catch(err => {
console.log(account); //nothing printed
reject(err);
});
});
}
my database connection in database/db.js
const mongoose = require('mongoose');
require('dotenv').config();
const database = {
connect: function () {
mongoose.connect(
process.env.MONGO_URI + '?retryWrites=true',
{ useNewUrlParser: true, useUnifiedTopology: true }
).then(
function () {
console.log('database connected successfully');
}).catch(error => {
console.log(error);
});
}
};
module.exports = database;
My whole controller code controllers/account.js:
Account = require('../models/account');
const bcrypt = require('bcrypt');
const saltRounds = 10;
authController = {
create: function (doc) {
return new Promise((resolve, reject) => {
bcrypt.hash(doc.password, saltRounds).then((hash) => {
doc.password = hash;
let promise = Account.create(doc);
promise.then((account) => {
console.log(account);
resolve(account);
}).catch((err) => {
console.log(err);
reject(err);
});
}).catch(err => {
console.log(err);
reject(err);
});
});
},
show: function (email) {
return new Promise((resolve, reject) => {
let filter = {email: email};
Account.findOne(filter).then((account) => {
resolve(account);
}).catch((err) => {
reject(err);
});
});
},
update: function (id, update) {
return new Promise((resolve, reject) => {
let filter = {_id: id};
Account.findOneAndUpdate(filter, update).then((account) => {
resolve(account);
}).catch((err) => {
reject(err);
});
});
},
destroy: function (id) {
return new Promise((resolve, reject) => {
let filter = {_id: id};
Account.findOneAndDelete(filter).then(() => {
resolve({deleted: true});
}).catch((err) => {
reject(err);
});
});
},
compare: function (doc) {
return new Promise((resolve, reject) => {
let filter = {email: doc.email};
Account.findOne(filter).then(user => {
bcrypt.compareSync(doc.password, user.password).then((result) => {
resolve(result);
}).catch((err) => {
reject(err);
});
}).catch((err) => {
reject(err);
});
});
}
};
module.exports = authController;
My model for account in models/account.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const accountSchema = new Schema({
first: {
type: String,
required: true
},
last: {
type: String,
required: false
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
role: {
type: String,
required: true
},
boards: [{
type: mongoose.Schema.Types.ObjectId, ref: 'Board',
required: false
}]
},
{
timestamps: true
});
Account = mongoose.connection.model('User', accountSchema);
module.exports = Account;
my test.js code:
const accountCtrl = require('./controllers/account');
const account = {
first: "User 1",
last: "Last 1",
email: "email1#tasks.com",
password: "password",
role: "test",
};
accountCtrl.create(account).then((result) => {console.log(result)}).catch((err) => {console.log(err)});

Related

How can i get list of customers between a date range?

How can i get list of customers between a date? There will be a starting date and an ending date picker in my frontend react app, but i dont know how to get the data in a specific date range uisng mongoose in my express app. Im posting my mongoose model and router code below, a little help will be appreciated --
mongoose model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const customerSchema = new Schema(
{
name: {
type: String,
required: true,
max: 50,
},
phone: {
type: String,
required: true,
max: 12,
},
address: {
type: String,
required: true,
max: 100,
},
pin: {
type: String,
required: true,
max: 6,
},
remarks: {
type: String,
max: 50,
},
isConverted: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
);
const Customer = mongoose.model(
'Customer',
customerSchema
);
module.exports = Customer;
route
const router = require('express').Router();
const Customer = require('../models/Customer');
router.post('/add', (req, res) => {
const newCustomer = new Customer({
name: req.body.name,
phone: req.body.phone,
address: req.body.address,
pin: req.body.pin,
});
newCustomer
.save()
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error creating a new customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/list', (req, res) => {
Customer.find()
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/getbyphone/:phone', (req, res) => {
Customer.findOne({ phone: req.params.phone })
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/getbyname', (req, res) => {
Customer.findOne({ name: req.body.name })
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.put('/:id', (req, res) => {
Customer.findByIdAndUpdate(req.params.id, {
remarks: req.body.remarks,
isConverted: req.body.isConverted,
})
.then((response) => {
res.send('Successfully updated');
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/:id', (req, res) => {
Customer.findById(req.params.id)
.then((cx) => {
res.send(cx);
})
.catch((err) => {
res.status(500).json(err);
});
});
module.exports = router;
add new route like this
router.post('/getByDate', (req, res) => {
Customer.find({ createAt:{$gt: req.body.min,$lt:req.body.max })
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
and send data from front lime this
{
min:mindate,
max:maxdate
}

UnhandledPromiseRejectionWarning: TypeError: createUser is not a function

I am having a flow of registering a new user.
I am getting the error UnhandledPromiseRejectionWarning: TypeError: createUser is not a function
auth.js
const express = require("express");
const authrequests = express.Router();
const cors = require("cors");
var createUser = require("./export/authConstants");
// Register User
authrequests.post("/register", async (req, res) => {
const userData = {
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email,
phone: req.body.phone,
password: req.body.password,
created: new Date(),
};
await createUser(userData)
.then((res) => {
console.log(res)
if (res.status == 200) {
return res.status(200).json({ msg: 'Registered!' });
} else if (res.status == 405) {
return res.status(405).json({ error: 'User already exists' });
} else {
return res.status(400).json({ error: err });
}
})
.catch(err => {
return res.status(400).json({ error: err });
})
});
module.exports = authrequests;
authConstants.js
const customers = require("./../../models/customers");
var hashPassword = require("./util/bcrypt");
var jwtCreate = require("./util/jwt");
var sendMail = require("./util/mail");
var BASE_URL = require("./../constants/constants");
//register
createUser = (userData) => {
return new Promise(async (resolve, reject) => {
customers.findOne({ where: { email: userData.email } })
.then(async (user) => {
if (!user) {
var hashResponse = await hashPassword(userData.password)
if (hashResponse.msg) {
userData.password = hashResponse.msg
customers.create(userData)
.then(async (user) => {
if (user) {
var jwtResponse = await jwtCreate({ data: user.id, expiry: 172800 })
if (jwtResponse.msg) {
const url = `${BASE_URL}/auth/emailVerified/${jwtResponse.msg}`;
var mailResponse = await sendMail({
to: user.email,
subject: 'Email Verification',
html: `Click on the following link to verify your account: click here`
})
if (mailResponse.msg) {
resolve({ status: 200 })
} else {
reject({ error: mailResponse.err })
}
} else {
reject({ error: jwtResponse.err })
}
} else {
reject({ error: "oops..! user creation failed" })
}
})
.catch(err => {
reject({ error: err })
});
} else {
reject({ error: hashResponse.err })
}
} else {
resolve({ status: 405 })
}
})
.catch(err => {
reject({ error: err })
})
})
};
bcrypt.js
const bcrypt = require("bcrypt");
//hashing password
hashPassword = async (password) => {
await bcrypt.hash(password, 10, (err, hash) => {
if (hash) {
return { msg: hash };
} else {
return { error: err };
}
})
};
jwt.js
const jwt = require("jsonwebtoken");
var EMAIL_SECRET = require("./../../constants/constants");
//jwt creation
jwtCreate = async (data) => {
await jwt.sign(data.data, EMAIL_SECRET, { expiresIn: data.expiry }, (err, token) => {
if (token) {
return { msg: token };
} else {
return { error: err };
}
})
};
mail.js
const nodemailer = require("nodemailer");
var MAIL_HOST = require("./../../constants/constants");
var EMAIL_USER = require("./../../constants/constants");
var EMAIL_PASS = require("./../../constants/constants");
//mail send
sendMail = async (data) => {
let transporter = nodemailer.createTransport({
host: MAIL_HOST,
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: EMAIL_USER,
pass: EMAIL_PASS,
},
tls: {
rejectUnauthorized: false,
},
});
await transporter.sendMail({
from: EMAIL_USER,
to: data.to,
subject: data.subject,
html: data.html
}, (err, response) => {
if (token) {
return { msg: response };
} else {
return { error: err };
}
});
};
constants.js
const EMAIL_SECRET = "asdf1093KMnHGcvnkljvasdu09123nlasdasdf";
const MAIL_HOST = "mail.test.com";
const EMAIL_USER = "no_reply_auth#test.com";
const EMAIL_PASS = "JMkC+)*Lv";
const BASE_URL = "http://localhost:3001";
UnhandledPromiseRejectionWarning: TypeError: createUser is not a function
is there something I am missing out..? or the entire flow is wrong..?

Sequelize update information

I've been struggling with this issue for a day now and can't seem to figure out a way to resolve it. This is the code I'm running
Client side:
const nameInput = document.querySelector("#nameInput");
const urlInput = document.querySelector("#urlInput");
const rowAlert = document.querySelector(".alertAppend");
const divAlert = document.createElement("div");
const nameUpdate = async (e) => {
e.preventDefault();
fetch("/auth/updateName", {
method: 'POST',
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify({
name: nameInput,
url: urlInput,
})
})
.then(function (data) {
console.log('Request success: ', data);
})
.catch(function (error) {
console.log('Request failure: ', error);
});
};
submitName.addEventListener("click", nameUpdate);
API:
router.get("/updateName", auth, async (req, res) =>{
try {
const { name, url } = req.body;
const ime = name;
const uid = req.session.passport.user;
db.User.find({ where: { id: uid } })
.on('success', function (user) {
if (user) {
user.update({
name: ime,
webhook: url
})
.success(function () {})
}
})
res.json({ message: url});
} catch (err) {
if (err) res.status(500).json({ message: "Internal Error"})
}
});
For some reason it just runs the select query and never proceeds to update the user.
Chrome console output
Debug console output
Sequelize model in case it helps:
module.exports = function (sequelize, DataTypes) {
var User = sequelize.define("User", {
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
},
name: {
type: DataTypes.STRING
}
})
return User;
}
The issue was in the API, it's supposed to be router.post
router.post("/updateName", auth, async (req, res) =>{
const { ime, url } = req.body;
const uid = req.session.passport.user;
console.log(ime);
db.User.findOne({where: {id: uid}})
.then(record => {
let values = {
name: ime,
webhook: url
}
record.update(values).then( updatedRecord => {
console.log(`updated record ${JSON.stringify(updatedRecord,null,2)}`)
res.status(200).json({ message: "success"});
})
}
})
.catch((error) => {
// do seomthing with the error
throw new Error(error)
})
});
You can try the following code
await db.User.update({
name: ime,
webhook: url
}, { where: { id: uid } });
When defining your model I don't see the webhook field

Search for particular results with a certain string in GraphQL

I want to search with my query getFoodType to return results based on whether the foodType of particular restaurant/takeaway is a "Chicken","Pizza" etc
Like this foodType: "Chicken"
I've tried using arguments and mongoDB filters (it's a MongoDB server) but no luck.
Schema
const EaterySchema = new Schema({
name: {
type: String,
required: true
},
address: {
type: String,
required: true
},
foodType: {
type: String,
required: true
}
});
My Schema Types
type Eatery {
id: String!
name: String!
address: String!
foodType: String!
}
type Query {
eatery(id: String!): Eatery
eateries: [Eatery]
getFoodType(foodType: String): [Eatery]
}
My Resolver
getFoodType: () => {
return new Promise((resolve, reject) => {
Eatery.find({})
.populate()
.exec((err, res) => {
err ? reject(err) : resolve(res);
});
});
},
Current Query in Apollo Playground
{
getFoodType (foodType: "Chicken") {
id
name
address
foodType
}
}
I essentially want to return all the results with "Chicken" as a the foodType. Something like foodType: "Chicken".
First, you need to get the value of the foodType to be queried in Resolver
const resolvers = {
Query: {
getFoodType: (_, args) => {
const { foodType } = args
...
},
},
}
Then use foodType when querying
Eatery.find({ foodType })
Finally need to return the result
new Promise((resolve, reject) => {
return Eatery.find({ foodType })
.populate()
.exec((err, res) => {
err ? reject(err) : resolve(res)
})
})
Complete example
const resolvers = {
Query: {
getFoodType: (_, args) => {
const { foodType } = args
return new Promise((resolve, reject) => {
return Eatery.find({ foodType })
.populate()
.exec((err, res) => {
err ? reject(err) : resolve(res)
})
})
},
},
}
Use the async/await
const resolvers = {
Query: {
getFoodType: async (_, { foodType }) => {
try {
const eaterys = await Eatery.find({ foodType }).populate()
return eaterys
} catch (e) {
// Handling errors
}
},
},
}

GraphQL: Rootquery returns null [duplicate]

This question already has answers here:
Why does a GraphQL query return null?
(6 answers)
Closed 3 years ago.
I want to have a rootquery that returns every row within my table. But currently when I call that rootquery I only receive null. But one of my rootquery that only returns one row with a specific id does work. So where i am going wrong?
Rootquery's:
This one works
aanvraag:{
type: AanvraagType,
args:{id: {type: GraphQLID}},
resolve(parentValue, args){
const query = `SELECT * FROM aanvraag where id=${args.id}`;
return db.conn.one(query)
.then(data => {
return data;
})
.catch(err => {
return 'Error is: ', err
});
}
},
This one doesn't work
aanvragen:{
type: AanvraagType,
resolve(parentValue, args){
const query = 'SELECT * from aanvraag';
return db.conn.many(query)
.then(data => {
return data;
})
.catch(err => {
return 'Error is: ', err
});
}
}
This is the whole file if someone needs it:
const graphql = require('graphql');
const pgp = require('pg-promise')();
const axios = require('axios');
const db = {}
var cn = {
host: 'localhost', // server name or IP address;
port: 5432,
database: 'admin',
user: 'admin',
password: 'admin123'
};
db.conn = pgp(cn);
const {
GraphQLObjectType,
GraphQLID,
GraphQLString,
GraphQLSchema
} = graphql;
const TeamlidType = new GraphQLObjectType({
name: 'Teamlid',
fields: {
id: { type: GraphQLID },
email: { type: GraphQLString },
naam: { type: GraphQLString }
}
})
const ProjectType = new GraphQLObjectType({
name: 'Project',
fields:{
id: {type: GraphQLID},
naam: { type: GraphQLString },
type: { type: GraphQLString },
lead_naam: { type: GraphQLString },
lead_email: { type: GraphQLString },
teamlid:{
type: TeamlidType,
resolve(parentValue, args){
console.log(parentValue.id);
const query = `SELECT * FROM teamlid WHERE project_id=${parentValue.id}`;
return db.conn.many(query)
.then(data => {
return data;
})
.catch(err => {
return 'The error is', err;
});
}
}
}
})
const AanvraagType = new GraphQLObjectType({
name: 'Aanvraag',
fields:{
id: {type: GraphQLID},
naam: { type: GraphQLString },
email: { type: GraphQLString },
divisie: { type: GraphQLString },
afdeling: { type: GraphQLString },
team: { type: GraphQLString },
project:{
type: ProjectType,
resolve(parentValue, args){
const query = `SELECT * FROM project WHERE aanvraag_id=${parentValue.id}`;
return db.conn.one(query)
.then(data => {
return data;
})
.catch(err => {
return 'The error is', err;
});
}
}
}
})
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
teamlid: {
type: TeamlidType,
args: { id: { type: GraphQLID } },
resolve(parentValue, args) {
const query = `SELECT * FROM teamlid WHERE id=${args.id}`;
return db.conn.one(query)
.then(data => {
return data;
})
.catch(err => {
return 'The error is', err;
});
}
},
aanvraag:{
type: AanvraagType,
args:{id: {type: GraphQLID}},
resolve(parentValue, args){
const query = `SELECT * FROM aanvraag where id=${args.id}`;
return db.conn.one(query)
.then(data => {
return data;
})
.catch(err => {
return 'Error is: ', err
});
}
},
project:{
type: ProjectType,
args:{id: {type: GraphQLID}},
resolve(parentValue, args){
const query = `SELECT * FROM project where id=${args.id}`;
return db.conn.one(query)
.then(data => {
return data;
})
.catch(err => {
return 'Error is: ', err
});
}
},
aanvragen:{
type: AanvraagType,
resolve(parentValue, args){
const query = 'SELECT * from aanvraag';
return db.conn.many(query)
.then(data => {
return data;
})
.catch(err => {
return 'Error is: ', err
});
}
}
}
})
module.exports = new GraphQLSchema({
query: RootQuery,
mutation
})
So I already found my answer. I had to wrap 'aanvraag' in an GraphQLList. So this would work:
aanvragen:{
type: GraphQLList(AanvraagType),
resolve(){
const query = 'SELECT * from aanvraag';
return db.conn.many(query)
.then(data => {
return data;
})
.catch(err => {
return 'Error is: ', err
});
}
}
I am new to GrapQL but i hope this will help someone in the future.

Categories

Resources