Here you can see my API controller method:
//need to export the api methods.
var mongoose = require('mongoose');
var User = require('../models/user');
var crypto = require('crypto');
module.exports.create = function(req, res) {
//TODO: error checking.
var user = new User();
user.firstName = req.body.firstName;
user.lastName = req.body.secondName;
user.email = req.body.email;
user.salt = crypto.randomBytes(16).toString('hex');
user.password = crypto.pbkdf2Sync(req.body.password, user.salt, 1000, 64).toString('hex');
//console.log(user);
user.save(function(err) {
res.status(200);
});
};
Here is my model:
var mongoose = require('mongoose');
var crypto = require('crypto');
module.exports = mongoose.model('User', {
email: {
type: String,
unique: true,
required: true
},
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
hash: String,
salt: String
});
Strangely enough even though my req.body contains all the information that I am trying to set, when I log the user at the end the only things that seem to be getting set are the first name and the salt?
Does anyone know why this is? And could you show me the correct way to do it?
Thanks
Related
Trying to create a blog website where users can comment on posts. I was able to create different blog posts so now I am trying to implement the comment feature. In my routes/admin/comments.js file I was able to create a comments array and append each comment into the array. I am using EJS to try to display the comments which should be <%=comments%> but I am getting an error that says 'comments is not defined' even though I have defined it in:
Comment.find({})
.then(comments =>{
console.log(comments)
res.render('home/post', {comments})
})
})
What am i doing wrong? I am following the same method I did with creating posts.
models/Post.js Schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PostSchema = new Schema({
title:{
type: String,
required: true
},
description:{
type: String,
required: true
},
body:{
type: String,
required: true
},
comments:[{
type: Schema.Types.ObjectId,
ref: 'comments'
}]
},{usePushEach:true})
module.exports = mongoose.model('posts', PostSchema);
models/Comment.js Schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CommentSchema = new Schema({
username:{
type: String,
required: true,
},
body:{
type: String,
required: true
},
})
module.exports = mongoose.model('comments', CommentSchema)
routes/admin/comments.js file
const express = require('express');
const router = express.Router();
const Post = require('../../models/Post');
const Comment = require('../../models/Comment');
router.get('/', (req,res) =>{
Comment.find({})
.then(comments =>{
console.log(comments)
res.render('home/post', {comments})
})
})
//Finds the comments and makes it available as object
router.post('/', (req,res) =>{
Post.findOne({_id: req.body.id})
.then(post=>{
console.log(post)
const newComment = new Comment({
username: req.body.username,
body: req.body.body,
});
post.comments.push(newComment);
post.save()
.then(savedPost =>{
newComment.save()
.then(savedComment =>{
res.redirect('/')
})
})
})
})
module.exports = router;
Error : usr.findOneAndUpdate is not a function
Model:
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt')
var schema = new Schema({
email: { type: String, require: true },
username: { type: String, require: true },
password: { type: String, require: true },
creation_dt: { type: String, require: true },
tasks:[{type:{type:String}}]
});
module.exports = mongoose.model('User',schema)
i want to Add some Task in tasks array so i use post method for That and code is
Code:
router.post('/newTask', function (req, res, next) {
var dataa = {
pName: req.body.pName,
pTitle: req.body.pTitle,
pStartTime: req.body.pStartTime,
pEndTime: req.body.pEndTime,
pSessionTime: req.body.pSessionTime
}
var usr = new User(req.user)
usr.findOneAndUpdate(
{_id:req.user._id},
{$push:{tasks:dataa}}
)
try {
doc = usr.save();
return res.status(201).json(doc);
}
catch (err) {
return res.status(501).json(err);
}
})
i also read the documentation of findOneAndUpdate but i din't get solution please someone can Help out of this error....
Thank You.
You need to import your model into the file containing your routes. All mongoose methods are based off the schema that you define, not new instances you create.
For example, if you have a User model that looks like this:
// file is named user.js
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema ({
username: String,
password: String
})
module.exports = mongoose.model("User", userSchema)
You need to import the model so mongoose recognizes it as one
Like so (assuming the routes file and user model file are in the same directory):
const User = require("./user")
router.post("/newTask", (req, res) => {
User.findOneAndUpdate(//whatever you want to be updated)
})
Am creating a registration form where user needs to enter details of his emailid(username),password,DOB,Address,phoneno. All fields are mandatory here emailid acts as an username. I have designed my Mongoose Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User = new Schema({
username: String,
password: String,
phoneno: {
type: Number,
unique: true,
required: true
},
Address : {
type: String,
required: true
},
Dob: {
type: String,
required: true
}
},{
timestamps: true
});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User', User);
My user router is given below
var express = require('express');
var UserDetails = express.Router();
var userSchema=require('../models/user');
var passport = require('passport');
const mongoose = require('mongoose');
var Verify = require('./verify');
UserDetails.post('/register', function(req, res, next) {
var newUser = new userSchema({
username : req.body.email,
Dob : req.body.dob,
Address : req.body.address,
phoneno : req.body.phoneno
});
userSchema.register(newUser,req.body.password, function(err, user) {
if (err) {
console.log(err);
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
console.log(req);
console.log(res);
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
This is the json object am sending via PostMan
{"email":"kannaa.in","password": "abcdef","phoneno":96930,"address":"396 SM Road","dob":"14-05-1992"}
But in the console and postman it says bad request if i try to perform the operation.However it stores the value in DB. I couldn't find out the error.
So after no one answered i found out myself what is the error about PassportJS expects the request to contain req.body.username it doesn't matter how many other datas you send it needs req.body.username from the request side. So all i had to change was rather than email i set it as username in postman and it worked like charm.
My postman Data
{"username":"kannaa.in","password": "abcdef","phoneno":96930,"address":"396 SM Road","dob":"14-05-1992"}
I've been working on a Nodejs+Express+Mongoose API that handles user registration/login, everything works perfectly when a user signs up, but when the user wants to login it says it can't find the user. Let me show you the code:
module.exports.registerUser = (req, res) => {
var user = new User();
user.email = req.body.email;
user.name = req.body.name;
user.setPassword(req.body.password);
user.save((err) => {
var token;
token = user.generateJwt();
res.status(200);
res.json({
'token': token,
'user': user,
});
});
};
When I register (I'm testing this with Postman) I get this message, showing everything it's OK:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0ODg1MDcwNjUsImlhdCI6MTQ4ODQyMDY2NX0.GD0NehQ1EYEnOKx2OJWALpkHB8u5N_9Zjm1dcuEdl7I",
"user": {
"__v": 0,
"name": "Stack Overflow",
"email": "stackoverflow#stackoverflow.com",
"_id": "58b77f39cf5e8d5f3ffdb4ff"
}
}
The password gets hashed, that's why the JSON doesn't contain it.
And this is the code for user login:
module.exports.loginUser = (req, res) => {
var password = req.body.password;
var email = req.body.email;
User.findOne({'email': email}, (err, user) => {
if (err) {
res.status(500).json(err);
}
if (user) {
if (!user.validPassword(password)) {
res.status(401).send({
message: 'Wrong password.'
});
} else {
token = user.generateJwt();
res.status(200);
res.json({
'token': token,
'user': user
});
}
} else {
res.status(404).send({
message: 'No user was found.'
});
}
});
}
But every time I hit the login button on postman with the same password and email, I get this:
{
"message": "No user was found."
}
And this is the user schema:
'use strict'
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var crypto = require('crypto');
var jwt = require('jsonwebtoken');
var secret = require('../config/secret');
var userSchema = new Schema({
email: {
type: String,
required: true,
unique: true
},
name: {
type: String,
required: true
},
age: {
type: Number,
required: false
},
schoolID: {
type: String,
required: false,
unique: false
},
university: {
type: String,
required: false
},
area: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Area'
},
project: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Project'
},
hash: String,
salt: String
});
userSchema.methods.setPassword = (password) => {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
};
userSchema.methods.validPassword = (password) => {
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
return this.hash === hash;
};
userSchema.methods.generateJwt = () => {
var expiry = new Date();
expiry.setDate(expiry.getDate() + 1);
return jwt.sign({
_id: this._id,
email: this.email,
name: this.name,
exp: parseInt(expiry.getTime() / 1000),
}, secret.secret);
};
var User = mongoose.model('User', userSchema);
module.exports = User;
I can't find the solution to this problem, because the way I see it, everything should be working just nice. Any ideas on why this isn't working?
Update:
This is for checking the email is being sent correctly:
{
"message": "No user was found. User: stackoverflow#stackoverflow.com password: stackoverflow"
}
I keep getting the same error "User is not a function" when I call my API method.
Has anybody got an ideas why this might be.
Api method:
//need to export the api methods.
var User = require('../models/user');
var passport = require('passport');
module.exports.create = function(req, res) {
//TODO: error checking.
var user = new User();
console.log(req);
user.firstName = req.body.firstName;
user.secondName = req.body.secondName;
user.email = req.body.email;
user.setPassword(req.body.password);
user.save(function(err) {
res.status(200);
});
};
user model:
var mongoose = require('mongoose');
var crypto = require('crypto');
var userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
hash: String,
salt: String
});
userSchema.methods.setPassword = function(password){
};
userSchema.methods.validPassword = function(password) {
};
mongoose.model('User', userSchema);
Let me know if I need to enter any more files.
Thanks
You need to export the mongoose model you created at the end of the User Model file. Something like
module.exports = mongoose.model('User', userSchema);