@elo-dev

Как найти и отсортировать данные в модели?

Модель постов:
const PostScheme = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
    },
    text: {
      type: String,
      required: true,
    },
    tags: {
      type: Array,
      default: [],
    },
    viewsCount: {
      type: Number,
      default: 0,
    },
    imageUrl: String,
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
    author: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
  },
  { timestamps: true }
)


Модель комментариев
const CommentScheme = new mongoose.Schema(
  {
    post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' },
    text: { type: String, required: true },
    emojis: { type: Array, default: [] },
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  },
  { timestamps: true }
)

export default mongoose.model('Comment', CommentScheme)


Нужно найти сначала по id пост, затем в нем отсортировать комментарии по созданию, как я могу это сделать ?

Пробую что-то такое, но не работает
const postId = req.params.id

    const post = await PostModel.findById(postId)
      .select('comments')
      .populate('comments')
      .sort({ createdAt: 1 })
      .exec()
  • Вопрос задан
  • 33 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы