我正在try 创建一个调用,该调用将‘图像’和‘posts.Image’之间的所有图像组合在一起,并按createdAt排序.到目前为止,我有:
output = [Array(1), Array(3), {…}, {…}, {…}, {…}, {…}, {…}]
因此,它似乎是将这些数组合并到一个父数组中,而不是合并到一个单独的数组中.
我想要的是:
output = [{…},{…},{…},{…},{…},{…},{…},{…},{…},{…},{…},{…}]
以下是我的方案:
const deviceSchema = new Schema({
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
images: [{
url: {
type: String,
},
createdAt: {
type: Date,
}
}],
posts: [{
description: {
type: String,
},
images: [{
url: {
type: String,
},
createdAt: {
type: Date,
}
}],
createdAt: {
type: Date,
}
}],
});
以下是我的综合预测:
const images = await Device.aggregate([
{ $project: {
combinedImages: { $concatArrays: ["$images", "$posts.images"] }
}},
{ $match: { _id: id }},
{ $unwind: '$combinedImages' },
{ $sort: { 'combinedImages.createdAt': -1 }},
{ $skip: (page-1)*limit },
{ $limit: limit },
{ $group: { _id: '$_id', images: { $push: '$combinedImages'}}}
])