【问题标题】:Mongoose find documents if array contains a value如果数组包含值,猫鼬会查找文档
【发布时间】:2021-07-25 14:11:01
【问题描述】:

所以我有这个架构

const Document = new mongoose.Schema({
    _id:{
        type:Number
    },
    creationDate:{
    type:Date,
    default:Date.now(),
    },
    title:String,
    status:{
        type:String,
        default:status.PENDING
    },
    description: String,
    category:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Categories',
    }],
})

我如何找到他们的类别数组包含给定 id 的文档? 我的意思是像查询一样使用类别 id 获取所有文档

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

有一些方法可以实现这一点。 第一个是$elemMatch操作员:

const docs = await Documents.find({category: { $elemMatch: {$eq: 'yourCategory'} }});
// you may need to convert 'yourCategory' to ObjectId

第二个是$in$all 运营商:

const docs = await Documents.find({category: { $in: [yourCategory] }});

const docs = await Documents.find({category: { $all: [yourCategory] }});
// you can give more categories with these two approaches 
//and again you may need to convert yourCategory to ObjectId

$in 类似于 OR,$all 类似于 AND。欲了解更多详情,请查看此链接:https://docs.mongodb.com/manual/reference/operator/query/all/

第三个是aggregate()函数:

const docs = await Documents.aggregate([
    { $unwind: '$category' },
    { $match: { 'category': mongoose.Types.ObjectId(yourCategory) } }
]};

使用 aggregate() 您只能在类别数组中获得一个类别 ID。

【讨论】:

    【解决方案2】:

    我相信一个简单的find 查询就可以了。

    Document.find({'category._id': 'id'}, function (err, docs) {});
    

    Document.find({'category._id': 'id'})
    .then(docs => {
        console.log(docs)
    })
    .catch(error => {
        console.log(error)
    })
    

    当您使用引用时,您可以通过 _id 的 id 获取元素。

    现在您可能会注意到您只会看到 id 本身。要实际查看类别中的内容,您需要使用populate

    Document.find({
      'category._id': 'id'
    }).populate({
        path: 'category'
    }).exec((err, doc) => {
      if (!err) {
        console.log(doc)
      } else {
        console.log(err)
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 2021-10-15
      • 1970-01-01
      • 2014-02-03
      • 1970-01-01
      • 2020-07-25
      • 2014-12-16
      相关资源
      最近更新 更多