简体   繁体   中英

Mongoose Sort a query result on the last element of an array field's value

I have a mongoose schema like this:

    const chatRoomSchema = new mongoose.Schema({
       roomid: String,
       eventid: String,
       users: [String],
       messages: [
        {
          userid: String,
          message: String,
          createdOn: { type: Date, default: Date.now },
        },
      ],
});

I want to query all the chatrooms but I want to sort it on the basis of chatroom which got the latest chat message (chatroom with last createdOn message first).

I know that I can sort on the basis of first message's createdOn by using

Chatroom.find().sort({ "messages.0.createdOn": -1 })

but how could I sort it on the last message?

Chatroom.find().sort({ "messages.createdOn": -1 })

尝试这个 。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM