本文介绍了猫鼬,基于外键/填充键排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个猫鼬的架构(AgendaCompromissoSchemaprofissionaisSchema).

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

我想找到按profissional.name降序排列的所有AgendaCompromisso的集合.

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

//路由器

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

推荐答案

使用 $ lookup (执行左外部联接,类似于sql)可以解决此问题:

Using $lookup (which performs left outer join, similar to sql) in aggregation pipeline can solve this:

router.get('/',function(req,res,next){
    AgendaCompromisso.aggregate([
    {
        $lookup:
        {
            from: "profissionais", //use the name of database collection not mongoose model
            localField: "profissional",
            foreignField: "_id",
            as: "profissional_doc"
        }
    },

    {
        $unwind: "$profissional_doc"  //remove array
    },

    {
        $sort: {"profissional_doc": -1}  // or {"profissional_doc": 1} for ascending
    }
    ])
    .exec( (err,data) => {
        callback(err,data,res)
    })
});

请注意,要进行查找,您需要使用mongodb 3.2或更高版本.

Just a note, for lookup you need mongodb version 3.2 or greater.

这篇关于猫鼬,基于外键/填充键排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:13