【问题标题】:Filter by referenced property in the mongoose [duplicate]按猫鼬中的引用属性过滤[重复]
【发布时间】:2017-12-31 21:11:45
【问题描述】:

当我有一段关系时,我很难找到在猫鼬中查询某些内容的正确方法。

基本上我有一个带有 ObjectId 的文档与另一个文档相关(如下所示)。

但是当我尝试过滤引用的属性时,没有任何效果。 基本上,问题出在这一行 ".where({ "Recipe.Title": new RegExp("*") })"

// const configs
const config = require('./config');

// mongodb setup
const mongoose = require('mongoose');
mongoose.connect(config.database);
var Schema = mongoose.Schema

// recipe schema
const RecipeSchema = mongoose.Schema({
  Title: { type: String },
  Description: { type: String },
  Complaints: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Complaint' }],
}); 
const Recipe = mongoose.model('Recipe', RecipeSchema);

// complaint schema
const ComplaintSchema = mongoose.Schema({
  Recipe  : { type: mongoose.Schema.Types.ObjectId, ref: 'Recipe' },
  Message: { type: String }
});
const Complaint = mongoose.model('Complaint', ComplaintSchema);

/*
    after inserting some items
*/

Complaint
    .find()
    .populate("Recipe")
    .where({ "Recipe.Title": new RegExp("*") }) // this is not working!
    .exec((error, items) => {
        items.map((item) => {
            console.log(item);
        });
    });

有人有正确的方法解决吗?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    (1) new RegExp("*") 似乎不是一个有效的正则表达式,因为 * 是特殊的,意味着重复 0 次或更多次之前的任何内容,例如a* 表示 0 个或多个 a

    如果您尝试使用*,则需要escape itnew RegExp('\\*')

    (2) 我认为您最好使用match(请参阅查询条件和其他选项)。

    Complaint.find().populate({
        path: "Recipe"
        match: {
            title: new RegExp('\\*')
        }
    }).exec(...);
    

    虽然我相信这会引起所有投诉并使用匹配正则表达式的食谱填充这些投诉。

    如果你真的只想抱怨与正则表达式匹配的食谱,你最好反其道而行之。

    Recipe.find({ title: new RegExp('\\*') }).populate('Complaints').exec(...)
    

    或者使用aggregation,您可以使用$lookup 加入Recipes 集合并使用$match 过滤文档。

    编辑:我相信会是这样的

    Complaint.aggregate([
        // join Recipes collection
        {
            $lookup: {
                from: 'Recipes',
                localField: 'Recipe',
                foreignField: '_id',
                as: 'Recipe'
            }
        },
        // convert array of Recipe to object
        {
            $unwind: '$Recipe'
        },
        // filter
        {
            $match: {
                'Recipe.title': new RegExp('\\*')
            }
        }
    ]).exec(...)
    

    【讨论】:

    • 使用 match,我只会收到投诉,但使用 null 配方。但实际上我想要食谱标题与我的正则表达式匹配的投诉
    • @EduardoSpaki 是的,这就是为什么我添加了关于以相反方式执行此操作或进行聚合的最后评论。
    • 是的...我测试了它并且它有效...我一开始只是感到困惑...因为实际上 fromrecipes (小写),并且 .Title 具有大写 T
    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 2020-11-05
    • 2022-01-26
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多