【问题标题】:How to get latest log record based on log date of an array field within a nested JSON document in mongoose如何根据 mongoose 中嵌套 JSON 文档中数组字段的日志日期获取最新日志记录
【发布时间】:2021-11-07 22:37:24
【问题描述】:

我有这样的用户架构 const userSchema = new Schema({

电子邮件:字符串, 日志:[{logDate:日期,状态:字符串}]

} 日志包含系统的所有用户日志,主要是登录和注销。我想得到 某个用户的最后一个日志状态。然后我想更新那个字段

下面是我的代码。但它会返回所有日志:

User.findOne({email: user.email},{logs:{status:1, logDate:1}},{ sort:{'logs.logDate': -1} }, (err, log) = > { 如果(错误){

res.send({status: 401, message: 'DB Error'}) } 别的 { res.status(200).json(log); } });

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: mongoose


【解决方案1】:

使用这个聚合

User.aggregate([
  {
    "$unwind": "$logs"
  },
  {
    "$match": {
      user: 1,
      "logs.Date": 1,
      "logs.status": 1
    }
  },
  {
    $sort: {
      "log.Date": -1
    }
  },
  {
    "$limit": 1
  }
])
)

https://mongoplayground.net/p/ZDXlIaYsDvD

【讨论】:

  • 我正在使用猫鼬,而您的代码是用于 mongosh 的,但它不起作用。
  • 我不适合我,因为这是一种 mongosh 方法,我正在使用 mongoose。给出的错误是 db is not defined
  • 是的,我拼错了,我更新我的答案,请尝试一下
  • 好的,它正在工作。但是如何更新收到的字段?
  • 您要更新哪个字段?在这个阶段你有 _id 的文档,现在你可以更新它
猜你喜欢
  • 2018-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
相关资源
最近更新 更多