Mongoose,基于外来/填充密钥排序

时间:2017-06-02 14:22:17

标签: node.js mongodb mongoose

我有两个带有猫鼬的模式(AgendaCompromissoSchemaprofissionaisSchema)。

我想找到一组按AgendaCompromisso降序排序的所有profissional.name

我更喜欢单独的架构而不是嵌套文档。

我尝试了下一个代码但没有成功。

    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)
        })
    });

//路由器

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','name')
    .exec( (err,data) => {
       callback(err,data,res)
    })
});

//模式

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' );

1 个答案:

答案 0 :(得分:2)

在聚合管道中使用$lookup(执行左外连接,类似于sql)可以解决这个问题:

BitmapFactory.Options.inPurgeable = true

请注意,对于查找,您需要mongodb 3.2或更高版本。