【问题标题】:How to find a latest data in array in mongoose [duplicate]如何在猫鼬中找到数组中的最新数据[重复]
【发布时间】:2018-01-28 23:32:46
【问题描述】:

我有一个如下的对话模型:

const ConvoSchema = mongoose.Schema({
    convoId: {
        type: String,
        required: true
    },
    seller: {
        type: String,
        required: true
    },
    buyer: {
        type: String,
        require: true
    },
    product: [{ type: Schema.Types.ObjectId, ref: 'Post' }],
    messages: [{ type: Schema.Types.ObjectId, ref: 'Message' }]
})

我正在尝试在 Convo 中获取最新消息,但不知道该怎么做。有什么想法吗?

【问题讨论】:

  • 除非您使用$position$sort 修饰符将向数组添加项专门修改为$push,否则“最新”始终是“最后”项,因为添加新数组项“追加”到最后。因此,您始终可以在投影中使用$slice 获取“最新”条目。

标签: node.js mongodb mongoose mongoose-schema mongoose-populate


【解决方案1】:

_id 基本上包含其中的时间戳,因此您在.find() 中获得的第一个元素将是最旧的,最后一个元素将是最新的

所以通过添加类似的排序:{ _id: -1} 将为您提供最新数据

var Convo = mongoose.model('Convo', ConvoSchema); //init mongoose model

Convo.find()
     .limit(1)
     .sort({ _id: -1 })

如果您想要完整的文档列表,您可以删除 .limit()

================================================ =========================

抱歉没有正确阅读,

最新消息,

Convo.findOne({}, response => {
   var data = response.toObject();
   latestMessage = data.messages.pop()
})

【讨论】:

  • 问题询问“消息数组”中的最后一项(“试图获取最新消息”)。您正在返回最后一个“文档”,而不是“文档内”数组中的最后一项。
  • 只需在消息数组上使用.pop()。或data.messages[ data.messages.length - 1 ] 也会给你正确的结果。
  • 还要确保使用.toObject() 将模型克隆到静态对象,因此如果您使用.save() 在同一个调用中保存模型。您不会使用 .pop() 意外删除最新消息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 1970-01-01
  • 2019-03-28
  • 2014-01-14
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多