Create subquery in Mongoose

Asked

Viewed 25 times

1

Which brings the following table

________________________________________
 id  |  descricao  |  ip  |  id_parent | 
  1  |   Teste     | 14   |   0        |    
  2  |   Outro     | 15   |   1        |    
  3  |   Meter     | 16   |   1        |    
  4  |   Tra       | 17   |   2        |  

I have the following query in Mysql

"SELECT  m.id
        ,m.descricao
        ,m.ip
        ,m.id_parent
        ,( SELECT COUNT(*) FROM medidor WHERE medidor.id_parent = m.id GROUP BY medidor.id_parent ) total
  FROM medidor m
  WHERE m.id_parent = 0

Which brings the following result

________________________________________________
 id  |  descricao  |  ip  |  id_parent |  total
  1  |   Teste     | 14   |   0        |    2

Where this table is self-related. The id_parent column is the main id code and the total column is the result of how many other items are associated with that id.

My scheme is like this:

const MedidorSchema = new mongoose.Schema(
    {
        descricao:{type:String},
        ip:{type:String},
        observacao:{type:String},
        sn_capacitor:{type:String},
        sn_controlar:{type:String},
        ip_controlado:{type:String},
        sn_automatico:{type:String},
        id_parent:{type: String},
    },
    {
        collection:"medidor",
        versionKey: false
    }
)

I’d like that result to come:

{
  _id: ObjectId("O1092kdsowo0203lldld"),
  descricao: "Teste",
  ...
  total: 2
}

I’m trying to do it like this:

return MedidorSchema.findOne({id_parent: _id}, (err, medidores: any)=>{
        MedidorSchema.countDocuments({id_parent: medidores._id}, (err, result)=>{
            medidores.total = result
        })
    })

How do I subquery Mongoose?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.