I'm making a friend finder application. I want to restrict the users to only one post. Here's what I have so far:
router.post("/", middleware.isLoggedIn, (req, res) => {
//get data from form and add to friendfinder array
var rank = req.body.rank;
var discord = req.body.discord;
var valorantid = req.body.valorantid;
var author = {
id: req.user._id,
username: req.user.username,
};
var newFriend = {rank:rank, discord:discord, valorantid:valorantid, author:author};
//create a new friend finder entry
Lookinglist.create(newFriend, function(err, newlyCreated){
if(err){
console.log(err);
} else {
//redirect back to frinedfinder page
res.redirect("friendfinder");
}
});
});
Do you have a route for /friendfinder?
if yes, use this
res.redirect("friendfinder");
Related
I am attempting to build a basic Vue.js Express profile interface that returns profile info of a specific user based on a route parameter id associated with each user. The .get() request in Vue.js is set up as the following:
created () {
let uri = `http://localhost:3000/users/${this.$route.params.id}`;
this.axios.get(uri).then((response) => {
this.profile = response.data;
});
},
The corresponding GET route in Express.js is set up as the following:
// mongodb
const mongo = require('mongodb').MongoClient;
const url = '...'; // connection url
const usersDB = 'users'; // users db name
app.get('/users/:id', function(req, res) {
let id = req.params.id;
var users;
const findUsers = function(db, callback) {
const collection = db.collection('documents');
// no query filter
collection.find({}).sort( {username: 1} )
.toArray(function(err, docs) {
users = docs;
callback(docs);
});
}
mongo.connect(url, function(err, client) {
// assert.equal(null, err);
const db = client.db(usersDB);
findUsers(db, function() {
// send users
res.status(200).send(users);
client.close();
});
});
});
In the above Express route, I added let id = req.params.id with the intention of prompting this route to respond with specific user info based on req.params.id. I am not sure how to further configure this route to actually return such info based on id. I tried implementing the following in the route:
collection.find({_id: mongo.ObjectId(req.params.id)})
instead of using:
collection.find({}).sort( {username: 1} )
...but that did not work. Any idea how to set up this route to return data based on req.params.id? Thanks!
UPDATED EXPRESS ROUTE
// get all users
app.get('/users/:id', function(req, res) {
var o_id = new mongo.ObjectID(req.params.id))
// get all users
var users;
const findUsers = function(db, callback) {
const collection = db.collection('documents');
// no query filter
collection.find({'_id': o_id})
.toArray(function(err, docs) {
users = docs;
callback(docs);
});
}
mongo.connect(url, function(err, client) {
const db = client.db(usersDB);
findUsers(db, function() {
// send users
res.status(200).send(users);
client.close();
});
});
});
It seems the results aren't returned because of ObjectId comparision not working. Creating new ObjectID using the id from req.params and then doing collection.find should bring back the results
var o_id = new mongo.ObjectID(req.params.id);)
collection.find({'_id': o_id});
I am creating a basic friend request feature. This is one of the function I am working on, when Ajax send the post request it shows 404. It works if I put the code directly in the server.js file but I am trying to organize the code. Any solution? Thanks!
client.pug make a ajax request when user add friend by using email and hit submit
$('#addFriend').on('click', function(ev) {
ev.preventDefault();
var searchByEmail = $('#searchByEmail').val();
$.ajax({
type: 'POST',
url: '/add',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: {
email: searchByEmail
},
success: function(data) {
console.log('success');
}
});
document.getElementById("searchByEmail").value = "";
$('#userModal').modal('hide'); });
controllers/friend.js
const express = require('express');
const app = express();
const User = require('../models/user');
const bodyParser = require('body-parser');
var friendRequest = function() {
app.post('/add', function(req, res) {
var requestToEmail = req.body.email;
console.log(requestToEmail);
User.findOne({
email: requestToEmail
}, function(err, email) {
if (!email) {
console.log('cannot find the email', err);
return res.send(err);
}
/*
Add into database
Display the friend list
*/
})
});
} // End friend request
module.exports = friendRequest;
server.js include and use the module
const friendInvite = require('./controllers/friend');
app.use('/friend', friendInvite);
file structure
- server.js
- controllers
- friend.js
- views
- client.pug
Try change your code on controllers/friend.js like below :
const express = require('express');
const app = express();
const User = require('../models/user');
const bodyParser = require('body-parser');
var friendRequest = function() {
app.post('/add', function(req, res) {
var requestToEmail = req.body.email;
console.log(requestToEmail);
User.findOne({
email: requestToEmail
}, function(err, email) {
if (!email) {
console.log('cannot find the email', err);
return res.send(err);
}
/*
Add into database
Display the friend list
*/
//add this response to client side
res.json({ 'status': '200', 'desc': 'Success' });
})
});
} // End friend request
module.exports = friendRequest;
you must send response to client side what is sign if the data has saved.
maybe you can try to check snippets code here :
https://github.com/egin10/node_mongoose/blob/master/routes/student.js
I didn't see response in your app.post()
So it will be 404(Not found).
When you find a User, you can response something.
For example, a 'success' message and friend list.
app.post('/add', function(req, res) {
res.json(['success', friend list]);
});
I'm attempting to create a form to collect email addresses. The email address POSTs to /dreamjob.
When I try to access the list on /emails no error shows up but the page does not load & times out. I cannot figure out the issue. How would I change my code to correct this? Thank you!
router.post("/dreamjob", function(req, res){
//Create Email
Email.create(req.body.email, function(err, newEmail){
if(err){
res.render("station.ejs");
} else {
newEmail.save();
console.log(req.body.email)
}
});
});
//All Emails:
router.get("/emails", function(req, res){
Email.find, function(err, email){
if (err){
console.log("ERROR!");
} else {
res.render("emails", {Email: email});
}
}
});
Model:
var mongoose = require("mongoose");
var emailSchema = new mongoose.Schema({
email: String
});
module.exports = mongoose.model("Email", emailSchema);
When you create an email, you're only responding to the request in case of error, try something like this:
Email.create(req.body.email, function(err, newEmail){
if(err){
res.render("station.ejs");
} else {
newEmail.save();
console.log(req.body.email);
res.send(200); // reply to the http request here
}
});
I am trying to use controllers to modify a page according to the user.
I am using this:
$http.get('/someUrl').then(function(response){
$scope.firstname = response.data;
});
What I am trying to do is, get each of the fields from my database and use them accordingly.
If this is my schema and I already have a person stored in the database:
var personSchema = new mongoose.Schema({
firstname: {type: String, required: true, },
lastname: {type: String, required: true}
});
var person = mongoose.model('People', personSchema);
module.exports = person;
What URL will I use in '/someUrl' to get the firstname of the person that is currently signed in?
Also, am I missing any functionality that I need to execute this?
EDIT:
My route
router.post("/update-profile", function(req, res) {
if (!req.session.user) {
return res.status(401).send();
}
var firstname = req.body.firstname;
var lastname = req.body.lastname;
var newProfile = new UserProfile();
newProfile.firstname = firstname;
newProfile.lastname = lastname;
console.log(newProfile);
newProfile.save(function(err, savedProfile) {
if (err) {
console.log(err);
return res.status(500).send();
} else {
res.render("profile");
return res.status(200).send();
}
});
});
Get a person object from the url.
$http.get('/user?id=5').then(function(response){
$scope.user = response.data;
});
Where the id is the user id.
Then in your html you can use {{user.firstName}}.
You could also pass in req.user to the page when it loads, so you wouldn't need to do another get.
res.render('page',{user:req.user});
Then (in ejs)
$scope.user = <%=user%>;
What I feel is, you should have an end-point /api/users/:id that should expect an _id as request parameter.
So your get request would be like :
$http.get('/someUrl/' + current_logged_in_user_id).then(function(response){
$scope.firstname = response.data;
});
And your backend code would be something like:
app.get('/someUrl/:id', function(req, res){
User.findById(req.params.id, function (err, user) {
if(user) res.json(user.firstName);
});
});
Now from the information that you provided, that's the best I can tell you. You can use DaftMonk's Angular Fullstack Generator. It creates the whole Authentication Boilerplate for you. It automatically get user details based on session_id and adds the user to req.user. So in the request handler, you can simply get the requesting user's details by using req.user
I am currently attempting to create a .post function for a schema with document reference. However, I am not sure how I can retrieve the ObjectID of the document reference from another collection.
Board.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoardSchema = new Schema({
boardname: String,
userid: {type: Schema.ObjectId, ref: 'UserSchema'}
});
module.exports = mongoose.model('Board', BoardSchema);
User.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: String
});
module.exports = mongoose.model('User', UserSchema);
routes.js
router.route('/boards')
.get(function(req, res) {
Board.find(function(err, boards) {
if(err)
res.send(err);
res.json(boards);
});
})
.post(function(req, res) {
var board = new Board();
board.boardname = req.body.boardname;
User.find({username: req.body.username}, function(err, user) {
if(err)
res.send(err);
board.userid = user._id;
});
board.save(function(err) {
if(err)
res.send(err);
res.json({message: 'New Board created'});
});
});
To create the board, I include a boardname and a username in my request. Using the username, I do a User.find to find the specific user and assign it to board.userid. However, this does not seem to be working as board.userid does not appear.
Any help would be greatly appreciated!
Thank you!
EDIT
A better explanation of what is required is that I have an existing User collection. When I want to add a new document to Board, I would provide a username, from which I would search the User collection, obtain the ObjectId of the specific user and add it as userid to the Board document.
I believe you are looking for population
There are no joins in MongoDB but sometimes we still want references
to documents in other collections. This is where population comes in.
Try something like this:
//small change to Board Schema
var BoardSchema = new Schema({
boardname: String,
user: {type: Schema.ObjectId, ref: 'User'}
});
//using populate
Board.findOne({ boardName: "someBoardName" })
.populate('user') // <--
.exec(function (err, board) {
if (err) ..
console.log('The user is %s', board.user._id);
// prints "The user id is <some id>"
})
Sorry, I solved a different problem previously. You'll probably want to use the prevoius solution I provided at some point, so I'm leaving it.
Callbacks
The reason the userid is not on the board document is because User.find is asynchronous and is not assigned at the moment board.save(...) is called.
This should do the trick:
(Also, I added a couple of returns to prevent execution after res.send(...))
.post(function(req, res) {
var board = new Board();
board.boardname = req.body.boardname;
User.find({username: req.body.username}, function(err, user) {
if(err)
return res.send(err); //<-- note the return here!
board.userid = user._id;
board.save(function(err) {
if(err)
return res.send(err); //<-- note the return here!
res.json({message: 'New Board created'});
});
});
});