(Mongoose) How to get user._id from session in order to POST data including this user._id
A bit different but:
User Model:
var UserSchema = new mongoose.Schema({ username: String, password: String});
Tasks Model:
var taskSchema = mongoose.schema({ text: String, author: { id: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, username: String }});module.exports = mongoose.model("Task", taskSchema);
Create a task with post route:
var text = req.body.text;var author = { id: req.user._id, username: req.user.username};var newTask = {text: text, author: author};Task.create(newTask, function(err, addedTask){ // what you wanna do});
Similarly with edit/update you can use a put route (edit) and delete route (method override for delete) with a 'checkTaskOwnership' middleware and then
Task.findByIdAndUpdate / Task.findByIdAndRemove
I think you should store user's _id
in session. To store _id
in the session use passport
. It handles Authentication really well, and on successful authentication it stores users credentials in req.user
. This req.user
is present in all the requests. So for any Route, you can get the user's _id
from req.user
object. you wont need to send user's _id from the Frontend.
While saving Task
use this:
var task = new Task({ title: req.body.title, owner : req.user._id});task.save(function(err){...});
Read PassportJS docmentation to get more detailed information about Session
and Authentication
.