首页 > 解决方案 > Mongoose,如何对集合中选定对象的日期进行排序

问题描述

我有这个猫鼬模式,我想根据它们的 createdAt 字段对菜单项进行排序

user:
...
menus: [
{
  name: { type: String },
  recipes: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Recipe',
    },
  ],
  image: {
    url: { type: String },
    type: {
      type: String,
      enum: avatarTypes,
    }
  },
  createdAt: {
    type: Date,
    required: true,
    default: Date.now
  }
},

],

在nodeJs中,当我获取它们时,我想根据菜单中的createdAt对它们进行排序(最新的优先)

这是我的代码,但它不起作用

const menus = await User.findOne({
  _id: id,
}).sort('-menus.createdAt')

标签: node.jsmongodbmongoosemongoose-schema

解决方案


推荐阅读