使用猫鼬填充过滤数据

使用猫鼬填充过滤数据

本文介绍了使用猫鼬填充过滤数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据结构数据库"和组件"

I have two data structures "database" and "components"

const DatabaseSchema = mongoose.Schema({
    components: [{ type: Schema.Types.ObjectId, ref: 'Components', required: false }],
});
const ComponentsSchema = mongoose.Schema({
    name: { type: String, required: true, trim: true, unique: true, lowercase: true },
    updatedAt: Date,
});

我想按组件名称过滤数据库中的所有项目

I want to filter all items in the database by component names

我正在使用的搜索规则

Database.find({
    components: { $elemMatch:  { name: /antr/i } }
}).populate({
    path: 'components',
    select: 'name -_id'
}).select(['descript','components']).exec( (err,data) => {
    console.log(err);
    res.json(data);
});

然而总是返回一个空元素

however always return an empty element

推荐答案

请试试这个:

正如我已经建议你可以使用这个:

As I've already suggested you can use this :

Database.find({})
    .populate({ path: 'components', match: { name: /antr/i }, select: 'name -_id' })
    .exec((err, data) => { console.log(err); res.json(data); });

因为您看到空数组是因为 match 中的过滤器查询没有在组件集合中找到合适的文档 w.r.t.数据库文档的components数组中的ObjectIds,这是正常的.也许你可以在代码中过滤掉那些,因为你不是那样看的,你可以使用聚合框架中的 mongoDB 的 $lookup ,它相当于 .populate() 来自猫鼬.

Since you're seeing empty array's is because of the filter query in match which doesn't find appropriate documents in components collection w.r.t. ObjectIds in components array of database document, this is normal. May be you can filter those out in code, as you aren't looking in that way, You can use mongoDB's $lookup from aggregation framework which is equivalent to .populate() from mongoose.

Database.aggregate(
    [{
        $lookup: {
            from: "components",
            "let": { "ids": "$components" },
            pipeline: [
                { $match: { $expr: { $in: ['$_id', '$$ids'] } } }],
            as: "dbComponentsArray"
        }
    }, { $unwind: '$dbComponentsArray' }, { $match: { 'dbComponentsArray.name': /antr/i } },
    { $group: { _id: '$_id', dbComponentsArray: { $push: '$dbComponentsArray' }, data: { $first: '$$ROOT' } } }, { $addFields: { 'data.dbComponentsArray': '$dbComponentsArray' } },
    { $replaceRoot: { 'newRoot': '$data' } }])

集合中的示例数据:

组件:

/* 1 */
{
    "_id" : ObjectId("5d481cd098ba991c0857959f"),
    "name" : "antracito",
    "updatedAt" : ISODate("2019-08-05T12:10:56.777Z"),
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("5d481cd098ba991c0857958f"),
    "name" : "anacito",
    "updatedAt" : ISODate("2019-08-05T12:10:56.777Z"),
    "__v" : 0
}

/* 3 */
{
    "_id" : ObjectId("5d481cd098ba991c0857951f"),
    "name" : "antracito",
    "updatedAt" : ISODate("2019-08-05T12:10:56.777Z"),
    "__v" : 0
}

/* 4 */
{
    "_id" : ObjectId("5d481cd098ba991c0857952f"),
    "name" : "anacito",
    "updatedAt" : ISODate("2019-08-05T12:10:56.777Z"),
    "__v" : 0
}

数据库:

/* 1 */
{
    "_id" : ObjectId("5d4979d52a17d10a6c8de81b"),
    "components" : [
        ObjectId("5d481cd098ba991c0857951f"),
        ObjectId("5d481cd098ba991c0857952f"),
        ObjectId("5d481cd098ba991c0857953f"),
        ObjectId("5d481cd098ba991c0857959f")
    ]
}

输出:

/* 1 */
{
    "_id" : ObjectId("5d4979d52a17d10a6c8de81b"),
    "components" : [
        ObjectId("5d481cd098ba991c0857951f"),
        ObjectId("5d481cd098ba991c0857952f"),
        ObjectId("5d481cd098ba991c0857953f"),
        ObjectId("5d481cd098ba991c0857959f")
    ],
    "dbComponentsArray" : [
        {
            "_id" : ObjectId("5d481cd098ba991c0857959f"),
            "name" : "antracito",
            "updatedAt" : ISODate("2019-08-05T12:10:56.777Z"),
            "__v" : 0
        },
        {
            "_id" : ObjectId("5d481cd098ba991c0857951f"),
            "name" : "antracito",
            "updatedAt" : ISODate("2019-08-05T12:10:56.777Z"),
            "__v" : 0
        }
    ]
}

这篇关于使用猫鼬填充过滤数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:10