Mongoose - 如何仅填充每个对象的嵌套数组中的第一个元素

问题描述

我正在尝试使用 NodeJS、Mongoose 和 React Native 创建一个聊天应用程序,我想向用户显示每个对话的最后一条消息。

我的对话架构中有一系列消息,如下所示:

const ConversationSchema = new mongoose.Schema({
    {...}
    messages: [
        {
            type: mongoose.Schema.Types.ObjectId,ref: 'Message'
        }
    ]
    {...}
})

我想知道是否有人可以帮助我只填充每个对话的第一条消息,以便回复:

conversations: [
    {
        "_id": ObjectId(...)
        "messages": [
             "text": "Last message"
        ]
    },{
        "_id": ObjectId(...)
        "messages": [
             "text": "Last message"
        ]
    },...
]

我目前正在使用 mongoose 的 populate 函数,但问题是如果只填充第一个对话:

Conversation.find().populate(query).exec((err,conversations => {
    {...}
})

const query = {
    {
        path: "messages",options: {
            limit: 1,sort: { _id: -1 }
        }
    }

}

注意:如果我没有指定 limit: 1sort: { _id: -1 },它会正确填充数组的所有元素,但这不是我想要的。

感谢任何能帮助我的人!

解决方法

您需要使用 perDocumentLimit 而不是 Limit

如果您需要正确的限制,您应该使用 perDocumentLimit 选项(Mongoose 5.9.0 中的新功能)。请记住,populate() 将为每个故事执行单独的查询,这可能会导致 populate() 变慢

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...