问题描述
我正在尝试使用 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: 1
和 sort: { _id: -1 }
,它会正确填充数组的所有元素,但这不是我想要的。
感谢任何能帮助我的人!
解决方法
您需要使用 perDocumentLimit 而不是 Limit
如果您需要正确的限制,您应该使用 perDocumentLimit 选项(Mongoose 5.9.0 中的新功能)。请记住,populate() 将为每个故事执行单独的查询,这可能会导致 populate() 变慢