gpt4 book ai didi

node.js - Mongoose ,根据外键/填充键排序

转载 作者:可可西里 更新时间:2023-11-01 10:15:33 24 4
gpt4 key购买 nike

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

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

我更喜欢单独的模式而不是嵌套文档。

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

    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 aggregation pipeline中(执行left outer join,类似于sql)可以解决这个问题:

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 或更高版本。

关于node.js - Mongoose ,根据外键/填充键排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44331221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com