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
Related
I have two models, defined in two seperate files
//models/Projects.js
const mongoose = require('mongoose');
export const projectSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
},
companyBackground: {
type: String,
required: false,
trim: true,
}
});
module.exports = mongoose.models.Project || mongoose.model('Project', projectSchema);
//models/User.js
const mongoose = require('mongoose');
const { projectSchema } = require('./Project');
const userSchema = new mongoose.Schema({
projects: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Project' }]
});
module.exports = mongoose.models.User || mongoose.model('User', userSchema);
I create a new user, and then create a new project, by pushing it to the user
import dbConnect from "utils/dbConnect";
import User from "models/User";
import Project from "models/Project";
export default async (req, res) => {
await dbConnect();
const { query: { id }, method } = req;
switch (method) {
case "POST":
try {
const user = await User.findById(id);
if (!user) {
return res.status(400).json({ success: false, message: "User not found" });
}
const newProject = new Project(req.body);
console.log(newProject);
user.projects.push(newProject);
await user.save();
if (!user) {
return res.status(400).json({ success: false, message: "Project not added"
}
res.status(200).json({ data: user });
} catch (error) {
res.status(400).json({ success: false, message: error.message });
}
break;
default:
res.status(400).json({ success: false });
break;
}
};
Bu here is the question. I can easily create a new project and save it to the user, but not make any updates.
Approaches I have tried include (but are not limited to):
https://stackoverflow.com/a/26157458/2947684
https://stackoverflow.com/a/47762417/2947684
To demonstrate the problems, see
const updateString = "projects.$." + req.body.property;
Project.findOneAndUpdate(
{ _id: req.body.projectid },
{ $set: { [updateString]: req.body.value } },
function (error, success) {
if (error) {
console.log('error');
console.log(error);
} else {
console.log("success");
console.log(success); //Returns null
}
}
);
The above returns null
And when I do this, I get
User.findById(userid)
.then((user => {
const project = user.projects.id(req.body.projectid); //user.projects.id is not a function
project.set(newContent);
return user.save();
}))
.then((user) => {
res.send(user);
})
.catch((error) => {
console.log('error: ', error.message);
res.status(400).json({ success: false, message: error.message });
});
Here is says that user.projects.id is not a function...
In mongo DB Atlas, I can see that the project has indeed been created.
This is turning me crazy, can someone tell me what I am doing wrong?
Would it be better, simply to create the projects as arrays (without making them as a mongoose object?)
When pushing to user.projects you should just add the _id since the property is defined as ObjectId[]:
try {
const user = await User.findById(id);
if (!user) {
return res.status(400).json({ success: false, message: 'User not found' });
}
const newProject = await Project.create(req.body);
console.log(newProject);
user.projects.push(newProject._id);
await user.save();
if (!user) {
return res
.status(400)
.json({ success: false, message: 'Project not added' });
}
res.status(200).json({ data: user });
} catch (error) {
res.status(400).json({ success: false, message: error.message });
}
Then, to update a Project you can simply do:
Project.findByIdAndUpdate(
req.body.projectid,
{ $set: { [req.body.property]: req.body.value } },
{ new: true }, // returns updated doc
function (error, success) {
if (error) {
console.log('error');
console.log(error);
} else {
console.log("success");
console.log(success); //Returns null
}
}
);
Created a login method but it spits out the token regardless of what is entered in the Userfields
This uses swagger API and I'm trying to develop the frontend and backend
I'm relatively new to nodejs/javascript
Any Help would be appreciated!
login.js
var form = document.getElementById('login')
form.addEventListener('submit', login)
async function login(event) {
event.preventDefault()
const username = document.getElementById('username').value
const password = document.getElementById('password').value
const result = await fetch('/v1/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username,
password
})
}).then((res) => res.json())
if (result.status === 'ok') {
// everythign went fine
console.log('Got the token: ', result.data)
localStorage.setItem('token', result.data)
alert('Login Successful')
return false;
} else {
alert(result.error)
}
}
userController.JS
login: async (req,res)=> {
const { userName, password } = req.body
const existUsername = await userModel.findOne({ userName: req.body.userName, password: req.body.password}).then((existUsername) =>{
if (existUsername){
res.status(400).json({status: 'Failed', message: `User was Not found`, data: null})
return;
}
try{
async() => {
await bcrypt.compare(password, req.body.password) }
// the username, password combination is successful
const token = jwt.sign(
{
id: userModel._id,
userName: userModel.userName
},
JWT_SECRET
)
res.json({ status: 'ok', data: token })
}
catch (e) {
res.status(400).json({status: 'Failed', message: `${e.message}`, data: null})
}
});
},
Hello I want to find posts which user has made ..
I do my request with JWT Token:
###
http://localhost:8080/forum/getByOwnerID
Authorization: Bearer {{token}}
This is my create function :
exports.create = async (req, res) => {
const { forumName, forumDescription } = req.body;
const token = req.token;
const forumExist = await Forum.findOne({ forumName: req.body.forumName });
if(forumExist){
res.status(400).send("Forum Exists already.");
}
try{
const owner = await User.findOne({userID:token._id});
if (!forumName || !forumDescription) {
res.status(400);
throw new Error("Please Fill all the feilds");
return;
}
else {
const newForum = new Forum({ forumName, forumDescription,user: owner.userID });
newForum.user = owner;
const createdNote = await newForum.save();
res.status(201).json(createdNote);
}
}catch(err){
res.status(400).send(err);
}
};
This is my function where I want to get the Posts which the user has made :
exports.getByToken = async (req, res, next) => {
const forum = await Forum.findById( {user: req.token._id} );
if (forum) {
res.json(forum);
} else {
res.status(404).json({ message: "Forum not found" });
}
res.json(forum);
}
And this is model which I have for Post:
const forumSchema = ({
forumName: {
type: String,
required: true,
},
forumDescription: {
type: String,
required: true,
},
user: {
type: Schema.Types.ObjectId,
ref: 'user'
},
published_on: {
type: String,
default: moment().format("LLL")
},
});
Everytime I do a request it has this error :
UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "{ user: 'admin' }" (type Object) at path "_id" for model "Forum"
my generate Token :
const generateToken = (_id, userID) => {
console.log('Signing token for ID ', _id,userID);
console.log('Secret key is ', process.env.JWT_KEY);
const token = jwt.sign({ _id,userID}, process.env.JWT_KEY, {
expiresIn: "30d",
});
console.log('Signed token: ', token);
return token;
};
As you are using findById, you should only send the id as argument function.
If you want to search with filter query, use find method
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..?
I am developing Rest APIs for some project and testing them using postman to send the data on my mLab server. But All I could get:
{
"error": {
"message": "ENOENT: no such file or directory, open 'C:\\Users\\Admin\\Desktop\\periodical API\\uploads\\2018-06-16T14:34:38.384Zhd-wallpaper-of-live.jpg'"
}
}
Here's my route code:
const mongoose = require("mongoose");
const Product = require("../models/product");
exports.products_get_all = (req, res, next) =>
{
Product.find()
.select("name price quantity date subject _id productImage")
.exec()
.then(docs => {
const response = {
count: docs.length,
products: docs.map(doc => {
return {
name: doc.name,
price: doc.price,
quantity: doc.quantity,
date: doc.date,
subject: doc.subject,
productImage: doc.productImage,
_id: doc._id,
request: {
type: "GET",
url: "http://localhost:3000/products/" + doc._id
}
};
})
};
res.status(200).json(response);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.products_create_product = (req, res, next) => {
const product = new Product({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
price: req.body.price,
quantity: req.body.quantity,
date: req.body.date,
subject: req.body.subject,
productImage: req.file.path
});
product
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "Created product successfully",
createdProduct: {
name: result.name,
price: result.price,
quantity: result.quantity,
date: result.date,
subject: result.subject,
_id: result._id,
request: {
type: "GET",
url: "http://localhost:3000/products/" + result._id
}
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.products_get_product = (req, res, next) => {
const id = req.params.productId;
Product.findById(id)
.select("name price quantity date subject _id productImage")
.exec()
.then(doc => {
console.log("From database", doc);
if (doc) {
res.status(200).json({
product: doc,
request: {
type: "GET",
url: "http://localhost:3000/products"
}
});
} else {
res
.status(404)
.json({ message: "No valid entry found for provided ID" });
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
};
exports.products_update_product = (req, res, next) => {
const id = req.params.productId;
const updateOps = {};
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
Product.update({ _id: id }, { $set: updateOps })
.exec()
.then(result => {
res.status(200).json({
message: "Product updated",
request: {
type: "GET",
url: "http://localhost:3000/products/" + id
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.products_delete = (req, res, next) => {
const id = req.params.productId;
Product.remove({ _id: id })
.exec()
.then(result => {
res.status(200).json({
message: "Product deleted",
request: {
type: "POST",
url: "http://localhost:3000/products",
body: { name: "String", price: "Number" }
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
I myself could not figure out the problem as I am a bit newbie on developing APIs.
On Linux servers ENOENT means
“No such file or directory”
said that the response you are getting is trying to let you know that,
The directory where you are trying to save, does not exist
The place of file you are looking for does not exist.
What I do recommend you is that you use your debugger tool to stop the execution before you try to get to the directory or where you try to read your file. That way you will understand where your code is failing.
Now many times when I get to this error, usually means that the directory does not exist but more frequently that you do no have permission to save the file.
Good luck, I hope it helps.
http://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Errors/unix_system_errors.html