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

135
Views
MongoDB NodeJS Devolver subdocumento

Estoy tratando de devolver un subdocumento que coincida con los campos de consulta. Solo quiero devolver el PIN que coincide con el usuario, que se encuentra en la colección de la cuenta. Esto es lo que tengo hasta ahora.

 router.post('/SelectUser', async(req, res) =>{ try{ const acc = await Account.findOne({"Email": req.body.Email}); if(!acc) throw Error('Email not found'); var user = await Account.findOne({"Users.Username":req.body.User.Username},{Users:{PIN:1}}); }

Esto genera todos los PIN asociados con una cuenta, que no es lo que quiero. Aquí están los esquemas y modelos que estoy usando:

Cuenta:

 const User = require('../Models/UserData'); const AccountSchema = new Schema({ // Email linked to this account Email:{ type:String, unique:true, required:true, index:true }, // Password for the account Password:{ type : String, required : true }, // Users on this account Users:{ type:[User], required:true } }); module.exports = mongoose.model('Account', AccountSchema);

Usuario:

 const UserSchema = new Schema({ // Name of the user Username:{ type:String, required:true, unique:true }, // PIN for each user PIN:{ type:Number, require:true } }); module.exports = UserSchema;
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Lo que está tratando de hacer sería bastante trivial en su aplicación (es decir, el código JS después de findOne ), pero si realmente desea hacerlo en mongodb, deberá usar la agregación. Cambia tu código a:

 const username = req.body.User.Username; const user = await Account.aggregate([ { $match: { "Users.Username": username } }, { "$project": { _id: false, USER: { $filter: { input: "$Users", as: "users", cond: { $eq: [ "$$users.Username", username ] } } } } }, { "$unwind": "$USER" }, { "$project": { USER_PIN: "$USER.PIN" } } ]); if(user.length){ console.log(user[0].USER_PIN) }else{ console.log('Username not found') }

Aquí está la consulta de agregación real para que juegues con ella: https://mongoplayground.net/p/o-xTTa8R42w

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!