Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda