Home > front end >  Get only one element from nested array Mongoose
Get only one element from nested array Mongoose

Time:06-14

this is my schema

const ElectionScheme= new mongoose.Schema({
id:{
    type:Number
},
description:{
    type:String
},
startDate:{
    type:Date
},
closeDate:{
    type:Date
},
certificatesMaxAmount:{
    type:Number
},
voters:[{
   idCard:Number,
   credential:String,
   names: String,
   surnames:String,
   gender:String,
   birthDate:Date,
   department:String,
   idCircuit:Number,
   phone:Number,
   mail:String,
   votesCount:Number,
   certificatesCount:Number
}]

})

Hello, I am trying to extract a single voter by filtering by their idcard from an array in a model, but I always get the complete list of voters. I try this

const Elections = require("../models/Elections");
Elections.findOne({ id: voteData.idElection,"voters.idCard":voteData.idCard, "candidates.idCard": voteData.idCandidate})
.select(["candidates", "voters", "electionMode"])
.lean().then(election => {...
}

enter code here

CodePudding user response:

I can't tell what's going on with the "candidates", but here's one way to filter/project what's returned from the "voters" array.

db.collection.find({
  "id": 3423423,        // <-- voteData.idElection
  "voters.idCard": 345  // <-- voteData.idCard
},
{
  "voters.$": 1
})

Try it with made up data on mongoplayground.net.

  • Related