I am trying to sort the products array based on the createdAt date.
My orders model
const itemSchema = new Schema(
{
productId: { type: Schema.Types.ObjectId, ref: 'Product' },
quantity: {
type: Number,
max: [10, 'Only 10 quantity of one item can be added.'],
required: true,
},
price: { type: Number, required: true },
},
{ timestamps: true }
);
const ordersSchema = new Schema({
products: [itemSchema],
userId: { type: Schema.Types.ObjectId, ref: 'User' },
});
I tried this according to a stack overflow post
const orders = await Order.findOne({ userId: req.userId })
.sort({ 'products.createdAt': -1 })
.slice('products', 10)
.populate({ path: 'products.productId', select: 'images title' });
But it does not return sorted array.
2
Answers
mongoplayground
Input:
Output:
Mongoose(v7.3.4) example :
Logs:
If you run current version (6.0) of MongoDB, then you can use $sortArray:
Mongo Playground