I am learning MEAN stack environment and I have a question.
I have a registration page, which registers the user in MongoDB:
// register.component.ts
register(){
this.http.post('http://localhost:3001/register', this.input)
.subscribe(
( next: any) => {
// TO-DO Success event
},
( error: any) => {
// TO-DO Error event
});
}
// app.js
app.post('/register', function(req, res){
db.collection('users').insertOne({
prenom : req.body.prenom,
nom: req.body.nom,
email : req.body.email,
password : req.body.password
})
})
It works pretty well, the problem is that for the connection, I use the _id:
// login.component.ts
login(id: string){
this.http.get('http://localhost:3001/login/' id).toPromise().then((data: any) => {
this.users = data
})
sessionStorage.setItem('id', id)
}
// app.js
app.get('/login/:id', function(req, res){
db.collection('users').findOne({ email: ObjectId(`${req.params.id}`)}, function(err, user){
if (err) throw err;
if (!user) {
console.log('User not found')
}
else if (user)
{
console.log('Found user: ' user.prenom)
}
})
})
How to make sure that when the user registers, it returns his _id directly, and like that I can put him in session:
sessionStorage.setItem('id', id)
CodePudding user response:
The db.collection.insertOne()
function returns the inserted document, see here. This means you can do a callback or async/await (whichever you prefer) for your insertOne()
function and then return the _id
by using the Express function res.json()
. In your frontend, you'll then get whatever content you put into res.json()
as a response. Happy coding! :)