Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

mongoose sort sub document

  1. User

    mongoose sort sub document

  2. Assistant

    To sort a sub-document in Mongoose, you can use the sort() method along with dot notation to specify the field you want to sort.

    Here's an example code snippet to illustrate how to sort sub-document in Mongoose:

    const schema = new mongoose.Schema({
      user_name: {
        type: String,
        required: true
      },
      posts: [
        {
          title: String,
          body: String,
          created_at: Date,
        }
      ]
    });
    
    const User = mongoose.model('User', schema);
    
    // sort posts by created_at field in descending order
    User.findOne({ user_name: 'johndoe' })
      .sort({ 'posts.created_at': -1 })
      .exec((err, user) => {
        if (err) {
          console.log(err);
        } else {
          console.log(user.posts);
        }
      });
    

    In this example, we have a User model that contains an array of posts. We want to sort the posts array by the created_at field in descending order.

    To achieve this, we call the sort() method on the findOne() query, passing in an object with the posts.created_at field and the -1 value to sort in descending order.

    The result of the query will be the sorted posts array for the matched user.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.