我有 3 个由 mongoose.ObjectId 连接的集合。
这是我的 2 个架构:
const clientSchema = new Schema({
name: {
type: String
},
phone: {
type: Number
},
registerDate: {
type: Date
},
referred: {
type: String,
default: null
},
payments: [{
type: mongoose.ObjectId,
ref: "PayInfo"
}]
}, {
timestamps: true
})
const Client = mongoose.model("Client", clientSchema)
const payInfoSchema = new Schema({
client: {
type: mongoose.ObjectId,
ref: 'Client'
},
date: {
type: Date
},
status: {
type: String,
default: 'Pendiente'
},
price: {
type: Number,
default: 40
},
type: {
type: String,
},
beneficiary: {
type: mongoose.ObjectId,
ref: 'User'
},
information: {
type: String
},
}, {
timestamps: true
})
const PayInfo = mongoose.model("PayInfo", payInfoSchema)
我想收到一个按 client.name 排序的 payInfo 列表。
首先我尝试了这个:
const paymentList = await PayInfo.find({ date: { $gte: dateStart, $lte: dateEnd } }).populate('client').sort({ 'client.name': 1 })
在第二个实例中,我尝试使用 aggregate
但我犯了错误...
const paymentList = await PayInfo.aggregate([
{
$lookup: {
from: 'Client',
localField: 'client',
foreignField: 'name',
as: 'client'
}
},
{
$unwind: {
path: $client
}
},
{
$sort: {
'client.name': 1
}
}
])
你能帮我吗??
谢谢!