2017-07-25 9 views
0

私は関係があるときに、マングースで何かを照会する正しい方法を発見しようとするのに苦労しています。mongooseで参照されているプロパティでフィルターをかける

基本的に私は別のドキュメントに関連するObjectIdを持つ1つのドキュメントを持っています(下記参照)。

しかし、参照のプロパティをフィルタリングしようとすると、何ももう機能しません。 は基本的に、問題は ".where({ "":新しい正規表現(" Recipe.Title *このラインである ")})"

// 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です。

あなたが*を使用しようとしている場合は、あなたがescape itする必要があります。new RegExp('\\*')

(2)私はあなたが(クエリ条件やその他のオプションを参照)matchを使用したほうが良いだと思います。

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

これはすべての苦情を受け取り、正規表現に一致するレシピを入力すると思われますが。

正規表現と一致するレシピで本当に苦情を出すだけなら、おそらく他の方法でやり直すほうがよいでしょう。

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

それとも、ドキュメントをフィルタリングするレシピコレクションと$matchに参加する$lookupを使用するaggregationを使用。

編集:私は**それは**試合を使用して

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 ** –

関連する問題