arrays - 如何在 Mongoose 中搜索填充数组 [包含 ref 的数组]

标签 arrays mongodb express mongoose mongoose-populate

我是 MEAN 堆栈开发的新手。请任何人告诉如何在 Mongoose 填充数组中搜索。该数组包含 ref.

讨论架构:

const discussionSchema = new Schema({
  user_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  subject_title: {
    type: String,
    required: true
  },
keywords: [
    {
      type: Schema.ObjectId,
      ref: 'Keyword',
      default: null
    }
}, 
{
  timestamps: true
}
)

关键字架构:

const keywordSchema = new Schema({
  keyword:{ 
    type: String,
    required: true,
    unique: true, 
  }
  
}, {
  timestamps: true
})

如何在包含关键字模型引用 ID 的关键字数组中搜索关键字字符串。

最佳答案

您可以使用 mongoose 聚合和 $lookup 运算符来实现此目的。 $lookup 用于加入集合,例如 populate

您必须先加入讨论和关键字,然后使用 $match 运算符搜索关键字。

假设 matchingKeyword 变量是您的查询。

let result = await DiscussionModel.aggregate([{
  $lookup: {
    from: 'keywords',
    localField: 'keywords',
    foreignField: '_id',
    as: 'keywords'
  }
}, {
  $match: {
    'keywords.keyword': matchingKeyword
  }
}]);

关于arrays - 如何在 Mongoose 中搜索填充数组 [包含 ref 的数组],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62890515/

相关文章:

带变量的 C 数组声明?

mongodb - Mongo go 驱动的 DocumentCount 不支持 $nearSphere

node.js - 在大文档中查找对象

c# - 分析 MongoDB 数据库以查看执行的查询

node.js - 如何使用express-fileupload过滤上传

javascript - 为什么我在应用程序中使用 mongoose 时无法检索任何结果

c++ - 我可以在 case 语句中使用数组吗?

php - 如何使用范围值在多维数组中搜索数据

c# - 遍历 BitArray 中所有可能的值组合

node.js - angular $resource delete 不会将正文发送到 express.js 服务器