Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Fetch data from MongoDB when the user register

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)
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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! :)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!