I need to find the events of a user but I can't retrieve the user since I can't pass the user id to route file of events.
app.js :
var Router = express.Router();
Router.use("/users/:uid/events", events);
events.js :
Router.post("/",function (req,res) {
User.findOne({
_id:req.params.uid
},function (err, foundUser) {
if(err){
res.json({success:false, message:"The user couldn't be found"});
}else{
console.log(req.params.uid);
console.log(foundUser);
var event = new Event();
event.title = req.body.title;
event.description = req.body.description;
event.save(function (err) {
if(err){
console.log(err);
}
});
foundUser.events.push(event);
}
})
});
As a result :
uid = undefined
foundUser = null
How can i pass uid parameter to the events.js?
I think this should work.
app.js:
var Router = express.Router();
Router.use("/users/", events);
events.js:
Router.post("/:uid/events", function (req,res) {
User.findOne({
_id:req.params.uid
},function (err, foundUser) {
if(err){
res.json({success:false, message:"The user couldn't be found"});
}else{
console.log(req.params.uid);
console.log(foundUser);
var event = new Event();
event.title = req.body.title;
event.description = req.body.description;
event.save(function (err) {
if(err){
console.log(err);
}
});
foundUser.events.push(event);
}
});
});
While Lazyexpert's answer is a way to solve this problem, I found what I have been exactly looking for today.
In order to pass uid from app.js
Router.use("/users/:uid/events", events);
to another route make sure that your router contains {mergeParams:true}
var express = require('express');
var Router = express.Router({mergeParams:true});
Related
I am working on a model here:
// user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');
// Define collection and schema for Users
let User = new Schema(
{
firstName: String,
lastName: String,
emailaddress: String,
password: String,
},
{
collection: 'users'
}
);
// authenticate input against database documents
User.statics.authenticate = ((emailaddress, password, callback) => {
User.findOne({ emailaddress: emailaddress })
.exec(function(error, user){
if(error){
return callback(error)
} else if (!user){
console.log('User not found!');
}
bycrypt.compare(password, user.password, function(err, result){
if(result === true){
return callback(null, user);
} else {
return callback();
}
})
})
});
module.exports = mongoose.model('User', User);
As you can see on my model I put the User.statics.authenticate on my codes to do some authentication. And then on my login.js route file:
const path = require('path');
const express = require('express');
const router = express.Router();
const db = require('../../database/index');
const axios = require('axios');
const User = require('../../database/models/user');
router.get('/', (req, res) => {
console.log('hi there this is working login get');
});
router.post('/', (req, res) => {
var emailaddress = req.body.emailaddress;
var password = req.body.password;
if( emailaddress && password ){
User.authenticate(emailaddress, password, function(err, user){
if(err || !user){
console.log('Wrong email or password!');
} else {
req.session.userId = user._id;
return res.redirect('/');
}
});
} else {
console.log('both fields are required...');
}
});
module.exports = router;
I called the function and then User.authenticate function and also I created the route for root w/c is the sample that I want to protect and redirect the user after login:
router.get('/', (req, res) => {
if(! req.session.userId ){
console.log('You are not authorized to view this page!');
}
User.findById(req.session.userId)
.exect((err, user) => {
if(err){
console.log(err)
} else {
res.redirect('/');
}
})
});
Upon clicking submit on my react form it returns this error:
TypeError: User.findOne is not a function
at Function.User.statics.authenticate (/Users/mac/Documents/monkeys/database/models/user.js:35:8)
I checked the Mongoose documentation and it seems I am using the right syntax.Any idea what am I doing wrong here? Please help! Sorry super beginner here!
PS. I've already installed and set up the basic express session too.
UPDATES:
I remove the arrow function from my call and use this.model.findOne but still get the typerror findOne is not a function
// authenticate input against database documents
User.statics.authenticate = function(emailaddress, password, callback){
this.model.findOne({ emailaddress: emailaddress })
.exec(function(error, user){
if(error){
return callback(error)
} else if (!user){
console.log('User not found!');
}
bycrypt.compare(password, user.password, function(err, result){
if(result === true){
return callback(null, user);
} else {
return callback();
}
})
})
};
findOne is a method on your User model, not your user model instance. It provides its async results to the caller via callback:
User.findOne({field:'value'}, function(err, doc) { ... });
I have a function that is inserting user credentials. I want to return value from a call back function...
var router = require('express').Router();
var User = require('../Models').users;
// function calling here
router.post('/signup', function (req, res)
{
var result = User.signUp(req.body);
res.send(result);
});
module.exports = router;
//implemetation of function
userSchema.statics.signUp = function signUp(obj) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
return user.save(function (err, newuser) {
if (err)
{
return 'Error occured during insertion..';
} else
{
return 'You have sign up successfully...';
}
});
}
I want to return the response as a string but it showing undefined. How should it be done?
var router = require('express').Router();
var User = require('../Models').users;
router.post('/signup', function (req, res)
{
var result = User.signUp(req.body, function(err, result){
if(err){
}
else{
res.send(result)
}
});
});
userSchema.statics.signUp = function signUp(obj, callabck) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
user.save(function (err, newuser) {
if (err)
{
callback( 'Error occured during insertion..');
} else
{
callback(null, newuser);
}
});
}
Use the callback i.e.
var router = require('express').Router();
var User = require('../Models').users;
// function calling here
router.post('/signup', function (req, res)
{
User.signUp(req.body,function(err,result){
res.send(result);
});
});
module.exports = router;
//implemetation of function
userSchema.statics.signUp = function signUp(obj,callback) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
return user.save(function (err, newuser) {
if (err)
{
callback('Error occured during insertion..',null);
} else
{
callback(null,'You have sign up successfully...');
}
});
}
Because of async nature .. Try this:
router.post('/signup', function (req, res)
{
var result = User.signUp(req.body, function(err, result){
if(err){}
else{res.send(result)}
});;
});
userSchema.statics.signUp = function signUp(obj, callabck) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
user.save(function (err, newuser) {
if (err)
{
callback( 'Error occured during insertion..',null);
} else
{
callback (null, 'You have sign up successfully...');
}
});
}
I'm a beginner at NodeJS / MongoDB so maybe it would be easy for you.
I have this simple code :
var MongoClient = require('mongodb').MongoClient;
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird')
MongoClient.connect("mongodb://localhost:27017/db_ldap_users", function(err, db) {
if(err) {
throw err;
}
console.log("connected to the mongoDB !");
});
var usersSchema = new mongoose.Schema({uid : String });
var Users = mongoose.model('Users', usersSchema);
app.get("/test", function(req, res) {
console.log("Service /test called");
var users = new Users();
users.uid = "James";
console.log("User created");
users.save(function(err) {
console.log("Callback");
if (err) {
console.log("error");
throw err;
}
console.log('added !');
res.send("ok");
});
});
Here is the output :
connected to the mongoDB !
Service /test called
User created
The problem is the user is never add to the DB. I have never entered in the callback, I don't know why, I have followed multiple tutorial and it seems to always works for them. Does someone has an idea ?
EDIT : I forget to add
mongoose.connect("mongodb://localhost:27017/db_ldap_users");
I was thinking the connection to the Database was enough Thanks
Thanks you
look this:
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/db_ldap_users");
var usersSchema = new mongoose.Schema({uid : String });
var Users = mongoose.model('Users', usersSchema);
app.get("/test", function(req, res) {
console.log("Service /test called");
var users = new Users();
users.uid = "James";
console.log("User created");
users.save(function(err) {
console.log("Callback");
if (err) {
console.log("error");
throw err;
}
console.log('added !');
res.send("ok");
});
});
I am using Mongoose and Express.js .
My Post request looks like this :
$('#update').on('click', function() {
var uname = $('#username').val();
var name = $('#name').val();
var json = {
user_name: name,
user_username: uname,
};
$.post("/saveprofile", json, function(data, error, xhr) {
if(!err)
window.location.href = "/feed";
});
});
This is how I'm handling the request :
app.post('/saveprofile', isLoggedIn, function(req, res) {
var username = req.body.user_username;
var uname = req.body.user_name;
User.findOne({$or:[{"facebook.email":req.user.facebook.email},{"local.email":req.user.local.email}]}, function (err, user){
user.name = uname;
user.username=username;
user.save();
res.send({redirect: '/feed'});
})
});
My documents get added into the db successfully but what I want is, when that happens it should redirect to a new page /feed . The above snippets mention 2 methods I've tried. But I've got no result . It doesn't redirect !
Edit:
Testing with exception handling gives undefined
app.post('/saveprofile', isLoggedIn, function(req, res) {
var username = req.body.user_username;
var uname = req.body.user_name;
try{
User.findOne({$or:[{"facebook.email":req.user.facebook.email},{"local.email":req.user.local.email}]}, function (err, user){
user.name = uname;
user.username=username;
user.save();
res.redirect("http://stackoverflow.com")
});
}
catch(ex){
console.log(ex) ;
}
});
Edit 2 :
I tried a sample request ...even it doesn't seem to redirect !
app.post('/test', isLoggedIn, function(req,res){
res.redirect("http://www.stackoverflow.com")
})
You can't make a redirection after an AJAX. You need to do it with Javascript.
So here is how we can do it,
Post request :
$('#update').on('click', function() {
var uname = $('#username').val();
var name = $('#name').val();
var json = {
user_name: name,
user_username: uname,
};
$.post("/saveprofile", json, function(data, err, xhr) {
if(!err)
window.location.href = data.redirect;
});
});
Server
app.post('/saveprofile', isLoggedIn, function(req, res) {
var username = req.body.user_username;
var uname = req.body.user_name;
User.findOne({$or:[{"facebook.email":req.user.facebook.email},{"local.email":req.user.local.email}]}, function (err, user){
user.name = uname;
user.username=username;
user.save(function(err){
if(!err)
res.send({redirect: '/feed'});
});
})
});
Link to Original Answer
Try res.redirect() instead :
res.redirect("/feed");
I got a 500 error and de description says: Mongoose is not defined when i call /delPost, but in the same file "post.js" the functions /addPost and /getPosts are working and use mongoose.model without problems. im a newbie and have searched a lot but can't fix that issue, hope you can help me.
routes/post.js
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
POST message to board (WORKING)
router.post('/addPost', function(req, res) {
if(req.body){
var post = mongoose.model('post');
var newpost = new post(req.body);
console.log(newpost);
newpost.save(function(err, newpost){
if(err) return res.send(200,{msg: 'not saved'});
})
console.log('save ok');
}
else{
res.send(200,{msg: 'no data received'});
}
});
GET messages from DB to show in HTML (WORKING)
router.get('/getPosts', function(req, res) {
var post = mongoose.model('post');
post.find(function(err, posts){
if(err) return console.log(err);
// console.log(posts);
res.send(posts);
})
});
DELETE a post (NOT WORKING)
router.post('/delPost/:rel', function(req, res){
// var mongoose = require('mongoose');
var post = moongose.model('post');
post.remove({_id: req.params.rel},function(err) {
if(err) return handleError(err);
console.log(err);
})
});
AJAX Call to /delPost route
function delPost(event){
event.preventDefault();
console.log('delpost');
var confirmation = confirm('Are you sure to delete this message?');
if(confirmation === true){
$.ajax({
type:'POST',
url: '/post/delPost/' + $(this).attr('rel')
}).done(function(response){
console.log('delete done.. ');
}).fail(function(response){
console.log('delete failed');
})
}
};