【问题标题】:Mongoose : query if array has length > 0Mongoose:查询数组的长度是否> 0
【发布时间】:2021-01-17 15:51:06
【问题描述】:

注意:

我已经尝试了其他问题的所有解决方案,但大多数都已经过时了

我需要查询请求者数量大于0的项目,做一个endpoint来获取通知。

型号:

const projectSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: 'User'
  },
  title: { type: String, required: true },
  description: { type: String, required: true, minlength: 300, maxlength: 3000 },
  comments: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment'
  }],
  state: { type: Boolean, default: true },
  requesters: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Profile'
  }]
}

这是我尝试过的查询,但似乎不起作用。 由于某种原因,它返回一个空白数组。

const projects = await Project.find({
    user: req.currentUser!.id,
    "requestersLength": { "$gt": 0 }
  });
  res.send(projects);

【问题讨论】:

标签: node.js mongodb express mongoose mongodb-query


【解决方案1】:

查询数组中包含至少一个元素的所有文档。

db.CollectionName.find({'arrayFiled.0': {$exists: true}})

在您的情况下,您的代码将如下所示

const projects = await Project.find({
    user: req.currentUser!.id,
    {'requesters.0': {$exists: true}}
  });
  res.send(projects);

您也可以使用$expr 查询运算符(3.6.+ 版中的新功能

允许在查询中使用聚合表达式 语言。

{ $expr: { <expression> } }

示例

 db.CollectionName.find({$expr:{$gt:[{$size:"$yourArrayField"}, 0]}})

阅读更多关于$exprhere

【讨论】:

    猜你喜欢
    • 2020-04-22
    • 2019-08-12
    • 2022-01-10
    • 2014-07-27
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    相关资源
    最近更新 更多