Reputation: 379
How to insert current logged in user into mongoose database . can anyone help me out .I have already created one schema and now wants to insert id of logged in user while inserting data in to schema.?
var userSchema = mongoose.Schema({ local : { email : String, password : String, } }); //and new scheme is. var contact_user_Schema = mongoose.Schema({ user_name:String, name: String, title: String, company_name: String, email: String, gender: String, mobile_no: String, alt_mobile_no: String, address: String, city: String, group_name: String, website_url: String, DOB:String });
now i wants to insert current user ID of logged in user .
for sample application you can follow Authentication in Node.js and Express.js with Passport.js part 1
I have got user details I am using EJS
<br>
<pre>
<p>
<strong>id</strong>: <%= user._id %><br>
<strong>email</strong>: <%= user.local.email %><br>
<strong>password</strong>: <%= user.local.password %>
</p>
</pre>
I have got user details main question is how to insert current user data into schema(table) while inserting data in to another schema(table) so in this case we are using one to many relationship .
Upvotes: 1
Views: 7850
Reputation: 1
In express.js it's simple to find the user's information. You can get this by calling req.user
to get the user object, and from that, use req.user.id
to get the user ID.
For example, you can use the following:
router.get('/user', function(req, res){
var user_id = req.user.id
});
You will populate the user_id
variable with the user id.
Upvotes: 0
Reputation: 2868
Its easy to get the logged in user using Passport.
Since you are using express framework, you can get the logged in user object from express middle ware.
If user is logged in, then you can get the current user in every express routing methods using the following property:
req.user
Do a console.log of it and see what all details you need to fetch from user.
Upvotes: 4
Reputation: 1306
Heres a local signup strategy I use for signing users up, creating a user object and adding it to the users collection in my mongoDB using mongoose.
var LocalStrategy = require('passport-local').Strategy,
User = require('mongoose').model('User')
module.exports = function(passport){
passport.use('local-signup', new LocalStrategy(function(username, password, done){
User.findOne({username: username}, function(err, user){
if(err) { return done(err) }
if(user) { return done(null, false) }
else {
var newUser = new User()
newUser.username = username
newUser.password = newUser.generateHash(password)
newUser.downloads = []
newPassword = []
newUser.save(function(err){
if(err) { throw err }
return done(null, newUser)
})
}
})
}))
}
If you want to add the user to the database for the session user you probably need to do something like this:
var newUser = req.user
newUser.save(....
Hope it helps.
Upvotes: 1