Friday, 2 June 2017

Sort using populate in mongoose

I have two schemas('AgendaCompromissoSchema' and 'profissionaisSchema') with mongoose.

I´d like to find a set of all 'AgendaCompromisso' sorted by 'profissional.name' descending .

I´d prefer separate schemas instead of nested documents.

I have uses the next code without success.

    router.get('/',function(req,res,next){  
        AgendaCompromisso.find({})
        .populate('profissional',name') //here I´d like the results sorted by 'name' descending
        .sort:{
           'profissional.name': -1 //Sort by name Added DESC
         }        
         .exec( (err,data) => {
           callback(err,data,res)
        })
    });

//router

const express = require('express');
const router = express.Router();
const AgendaCompromisso = require('../models/agendaCompromisso');
const callback=function(err,data,res){
     //console.log(data);
     if (err) return res.status(500).json(err);
     return res.status(200).send(data);
}   

//get all
router.get('/',function(req,res,next){  
    AgendaCompromisso.find({})
    .populate('profissional','nome')
    .exec( (err,data) => {
       callback(err,data,res)
    })
});

//schemas

var AgendaCompromissoSchema = new mongoose.Schema({
  profissional:{type:mongoose.Schema.Types.ObjectId, ref:'Profissional'},
  title:{type:String},
  slot_dateInit:{type: Date},
  slot_timeInit:{type: Date}
});
module.exports = mongoose.model('AgendaCompromisso', 

AgendaCompromissoSchema,'agendasCompromissos' );

var profissionaisSchema = new mongoose.Schema({
  name: {type: String, unique:true},
  cpf: {type: String},
});

module.exports = mongoose.model('Profissional', profissionaisSchema,'profissionais' );



via Luiz Alves

No comments:

Post a Comment