2017-07-25 28 views
0

我有一些困难的时候试图发现正确的方式来查询猫鼬中的东西,当我有一个关系。通过引用属性在猫鼬中筛选

基本上我有一个与ObjectId有关的另一个文档的文档(正如你可以看到以下)。

但是当我尝试过滤引用的属性时,什么都不起作用了。 基本上,问题是这条线 “。凡({ ”Recipe.Title“:新的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); 
     }); 
    }); 

是否有人有解决这个问题的正确方法?

回答

1

(1)new RegExp("*")似乎没有一个有效的正则表达式,因为*是特殊和手段重复0次或多次无论是之前它在例如a*表示0或更多a's。

如果您尝试使用*,你需要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加入食谱收集和$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(...) 
+0

,我就把投诉,但与** **空配方。但实际上我想要的投诉,食谱标题匹配我的正则表达式 –

+0

@EduardoSpaki正确的,这就是为什么我添加了最后的评论关于做或者做其他方式或做聚合。 – Mikey

+1

yeap ...我测试了它,它工作...我刚开始时感到困惑...因为实际上来自**的**是**食谱**(小写)和**。上** T ** –