mongodb - Filter by referenced property in the mongoose -
this question has answer here:
- querying after populate in mongoose 5 answers
i'm having hard times trying discovery right way query in mongoose when have relationship.
basically have 1 document objectid relating document (as can see bellow).
but when try filter property of reference, nothing works anymore. basically, problem line ".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 items */ complaint .find() .populate("recipe") .where({ "recipe.title": new regexp("*") }) // not working! .exec((error, items) => { items.map((item) => { console.log(item); }); });
does have correct way solve it?
(1) new regexp("*")
not seem valid regular expression because *
special , means repeat 0 or more times whatever before in e.g. a*
means 0 or more a
's.
if trying use *
, need escape it: new regexp('\\*')
(2) think you're better off using match (see query conditions , other options).
complaint.find().populate({ path: "recipe" match: { title: new regexp('\\*') } }).exec(...);
though believe complaints , populate recipes match regular expression.
if want complaints recipes matching regular expression, you're better off doing other way around.
recipe.find({ title: new regexp('\\*') }).populate('complaints').exec(...)
or using aggregation use $lookup join recipes collection , $match filter documents.
edit: believe like
complaint.aggregate([ // join recipes collection { $lookup: { from: 'recipes', localfield: 'recipe', foreignfield: '_id', as: 'recipe' } }, // convert array of recipe object { $unwind: '$recipe' }, // filter { $match: { 'recipe.title': new regexp('\\*') } } ]).exec(...)
Comments
Post a Comment