Search code examples
node.jsmongodbmongoose

How to sort object inside of array based on createdAt in mongoose?


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.


Solution

  • If you run current version (6.0) of MongoDB, then you can use $sortArray:

    db.collection.aggregate([
      {
        $set: {
          products: {
            $sortArray: {
              input: "$products",
              sortBy: { createdAt: 1 }
            }
          }
        }
      }
    ])
    

    Mongo Playground