I want to select all users except current longlined user using email address, I don't want to show his details so how it is possible in node js?
router.get('/', function(req, res, next) {
const jsonObj = jsonToken.verify(req.cookies.email, process.env.privateKey);
const userEmail = jsonObj.userEmail
console.log(userEmail)
userModel.find().exec((err, data)=> {
if (err) throw err;
res.status(200).json(data);
res.render('index', { title: 'Secret Santa', users: data });
})
You can add not equal to condition in your find query,
userModel.find({ email: { $ne: userEmail } }).exec((err, data)=> {
if (err) throw err;
res.status(200).json(data);
res.render('index', { title: 'Secret Santa', users: data });
})
Related
I'm developing full-stack,
with
Node,
Express,
Session-mysql,
passport...
like a title, my router.post has no res.
router.post('/', function(req, res) {
hasher({password: req.body.password, function(err, pass, salt, hash){
var account = {
authId: 'local:'+req.body.username,
username: req.body.username,
password: hash,
salt: salt,
displayName: req.body.displayName
};
var sql = 'INSERT INTO accounts SET ?';
conn.query(sql, account, function(err, results) {
if(err) {
console.log("signup_post_in_error");
res.status(500);
} else {
req.login(account, function(err) {
console.log(err);
req.session.save(function() {
res.redirect('/board');
})
})
}
});
}})
})
form(action='/signup' method='post')
when I click submit, there is no response.
I'm using PassportJS. I'm trying to let users edit their email address if needed. This is the code I have which is currently not working.
Any advice? Thank you!
app.post("/editprofile", middleware.isLoggedIn, function(req, res, next){
User.update({ id: req.session.passport.user }, {
email: req.body.email,
}, function(err, user) {
if (err) return next(err);
User.findById(req.user._id, function(err, user) {
if (err) return next(err);
console.log(err)
return res.render('landing.ejs', {
user:user
});
});
});
});
Consider using this and every thing will be fine
app.post("/editprofile", middleware.isLoggedIn, function(req, res, next){
User
.findOneAndUpdate({ _id: request.session.passport.user }, req.body.email)
.exec(function(err, user) {
if (err) return res.render(/* Your error template here */, {
err: err.message
};
return res.render('landing.ejs', {
user: user
});
});
}
}
Hope this helps!
So on my webpage www.groupwrites.com I am showing an Index of stories in the "Read" page. These stories currently show in the order of which they were created (i.e the newest ones on bottom). I am trying to figure out how to display them with the most recently created/updated one first. I am using mongoDB, node JS on cloud9. I have been trying to research and know that I should use updatedAt but I am not sure how to plug everything in. I am not sure how to update the timestamp for updatedAt in the put routes.
This is my code for the index:
// INDEX - show all stories
router.get("/browse", function(req, res, next){
// Get all stories from DB
Story.find({}, function(err, allStories){
if (err) {
return next(err);
} else {
// if user is logged in then render stories and any alerts
if(req.user) {
User.findById(req.user._id).populate({
path: 'alerts',
model: 'Alert',
match: { 'isRead': { $eq: false }}
}).exec(function(err, user) {
if(err) {
return next(err);
}
res.render("stories/index", {stories:allStories, alerts: user.alerts.length, page: 'browse'});
});
} else {
res.render("stories/index", {stories:allStories})
}
}
})
})
// CREATE - add new story to DB
router.post("/browse", middleware.isLoggedIn, function(req, res, next){
// get data from form and add to stories array
var title = req.body.title
var image = req.body.image
var desc = req.body.description
var category = req.body.category
var author = {
id: req.user._id,
username: req.user.username
}
var newStory = {title: title, image: image, description: desc, author: author, category: category}
// Create a new story and save to database
Story.create(newStory, function(err, newlyCreated){
if (err) {
return next(err);
} else {
// redirect back to stories page
req.flash("success", "Successfully published story!")
res.redirect("/browse")
}
})
})
This is the code for the content of the stories, (i.e when adding a chapter to the story):
// New Content
router.get("/stories/:id/content/new", middleware.isLoggedIn, function(req, res, next){
// Find story by id
Story.findById(req.params.id, function(err, story){
if (err) {
return next(err);
} else {
res.render("content/new", {story: story})
}
})
})
// Create Content
router.post("/stories/:id/content", middleware.isLoggedIn, function(req, res, next){
// Look up story using ID
Story.findById(req.params.id).populate({path: 'subscribors', model: 'User'}).exec(function(err, story){
if (err) {
return next(err);
} else {
Content.create(req.body.content, function(err, content){
if (err) {
return next(err);
} else {
if(story.subscribors.length) {
var count = 0;
story.subscribors.forEach(function(subscribor) {
// create alert for each subscribor and add to subscribor's alerts
Alert.create({follower: story.author.id, followed: subscribor, story: story, isUpdated: true}, function(err, newAlert) {
if(err) {
return next(err);
}
// console.log(newAlert);
subscribor.alerts.push(newAlert);
subscribor.save();
count+=1;
if(count === story.subscribors.length) {
// Add username and ID to content
content.author.id = req.user._id;
content.author.username = req.user.username;
// Save content
content.save();
story.content.push(content);
story.save();
req.flash("success", "Successfully added chapter!");
return res.redirect("/stories/" + story._id);
}
});
});
} else {
// Add username and ID to content
content.author.id = req.user._id;
content.author.username = req.user.username;
// Save content
content.save();
story.content.push(content);
story.save();
req.flash("success", "Successfully added chapter!");
return res.redirect("/stories/" + story._id);
}
}
});
}
});
});
// Content Edit Route
router.get("/stories/:id/content/:content_id/edit", middleware.checkContentOwnership, function(req, res){
Content.findById(req.params.content_id, function(err, foundContent){
if(err){
res.redirect("back")
} else{
res.render("content/edit", {story_id: req.params.id, content: foundContent})
}
})
})
// Content Update
router.put("/stories/:id/content/:content_id", middleware.checkContentOwnership, function(req, res){
Content.findByIdAndUpdate(req.params.content_id, req.body.content, function(err, updatedContent){
if(err){
res.redirect("back")
} else {
req.flash("success", "Successfully edited chapter!")
res.redirect("/stories/" + req.params.id)
}
})
})
While defining a Mongoose Schema,
1 for ascending and -1 for descending
Example:
"use strict";
var mongoose = require('mongoose');
var db= require('mongoose').models;
let findOrCreate = require('findorcreate-promise');
var abc= new mongoose.Schema({
name: String,
updated_At: { type: Date, default: Date.now } // like this you can define
});
mongoose.model('abc', abc);
and you can use this by :
db.abc.find({})
.sort({'updated_At':1}) //1 for ascending and -1 for descending
.exec(Your callback function)
this will make sorting from smallest updated_At date to largest.
Thanks
I have this rest API on nodejs as follows
router.route('/api/Customers')
.post(function(req, res) {
var Customer = new Customer();
Customer.name = req.body.name;
Customer.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Customer created!' });
});
})
.get(function(req, res) {
Customer.find(function(err, Customers) {
if (err)
res.send(err);
res.json(Customers);
});
});
router.route('/api/Customers/:Customer_id')
.get(function(req, res) {
Customer.findById(req.params.Customer_id, function(err, Customer) {
if (err)
res.send(err);
res.json(Customer);
});
})
.put(function(req, res) {
Customer.findById(req.params.Customer_id, function(err, Customer) {
if (err)
res.send(err);
Customer.name = req.body.name;
Customer.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Customer updated!' });
});
});
})
.delete(function(req, res) {
Customer.remove({
_id: req.params.Customer_id
}, function(err, Customer) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
How can I create endpoints for specific fields ? For example if I want to GET results for CustomerName, CustomerZip, etc .. Do I have to create separate end points for each field?
Are you using express.js as framework? In this case you can put optional params in your route, for example:
router.route('/api/Customers/:Customer_id?')
.post(function(req, res) {
...
})
.get(function(req, res) {
...
});
});
in this way :Customer_id will be optional and you can manage logic inside your route.
This is a working example:
app.route('/test/:param1?/:param2?')
.get( function(req, res, next) {
res.json({
'param1' : req.params.param1,
'param2' : req.params.param2
});
});
app.listen(8080);
this route supports:
/test
/test/1
/test/1/2
inside response you can see value of this params, I don't know how pass only param2 without param1.
I have the following controller code that works for index, show, create methods but the update fails when I include populate - what am I doing wrong?
// User List
index: function(req, res) {
User.find()
.populate('profile')
.exec(function(err, users) {
if (err) return res.json(err, 400);
if (!users) return res.json(users, 404);
res.json(users, 200);
});
},
// Single User
show: function(req, res) {
User.findOne({ username: req.param('username') })
.populate('profile')
.exec(function(err, user) {
if (err) return res.json(err, 400);
if (!user) return res.json(user, 404);
res.json(user, 200);
});
},
// Create User
create: function(req, res) {
User.create(req.body, function(err, user) {
if (err) return res.json(err, 400);
Person.create({user: user.id, slug: user.username}, function(err, profile) {
if (err) return res.json(err, 400);
User.update(user.id, {profile: profile.id})
.populate('profile')
.exec(function(err, user) {
if (err) return res.json(err, 400);
});
user.profile = profile;
res.json(user, 200);
});
});
},
// Update User
update: function(req, res) {
var username = req.param('username');
User.update({ username: username }, req.body)
.populate('profile')
.exec(function(err, user) {
if (err) return res.json(err, 400);
res.json(user, 201);
});
},
As per the documentation the update function takes a callback to which it passes the updated records.
Example from the doc :
// For example, to update a user's name,
// .update(query, params to change, callback)
User.update({
name: 'sally'
},{
phone: '555-555-5555'
}, function(err, users) {
// Error handling
if (err) {
return console.log(err);
// Updated users successfully!
} else {
console.log("Users updated:", users);
}
});
Applied to your code, it would look like this :
// Update User
update: function(req, res) {
var username = req.param('username');
User.update({ username: username }, req.body)
.exec(function(err, users) {
if (err) {
return res.json(err, 400);
}
var user = users.slice(0,1); // Take the first user in the array
User.findOne(user.id) // You may try something like User._model(user) instead to avoid another roundtrip to the DB.
.populate('profile')
.exec(function(err, user) {
if (err) {
return res.json(err, 400);
}
res.json(user, 201);
});
});
}
Jeremie your answer is correct in essence but has a few issues:
the user object returned by the update call and then sliced does not
have a populate function
slice the users list returns a list instead of the object desired
Personal preference but I also prefer the following which uses the exec call instead of the callback.
update: function(req, res) {
var id = req.param('id');
User
.update(id, req.params.all())
.exec(function(err, users) {
if(err) return res.json(err, 400);
var user = users[0];
console.log('ID', user.id);
User
.findOne(user.id)
.populate('profile')
.exec(function (err, user){
if (err) return res.json(err, 400);
res.json(user, 201);
});
});
},