If I have this Dishes Schema and I want to search about ingredients, comments, categories and steps of this documents how do I search.
var DishesSchema = new Schema({
created_at: {
type: Date,
default: Date.now
},
created_by: {
type: Schema.ObjectId,
ref: "User"
},
title: String,
description: String,
comments: [{ type: Schema.ObjectId, ref: 'Comment' }],
body: String,
picture: [String],
main_picture: String,
likes: [{
type: Schema.ObjectId,
ref: "User"
}],
ingredients: [{ type: Schema.ObjectId, ref: 'Ingredient' }],
categories: [{ type: Schema.ObjectId, ref: 'Category' }],
steps: [String]
});
I find the way to search ingredients, comments, categories but how to search steps
Dishes.find().or([
{ 'ingredients.name': new RegExp(name, "i") },
{ description: new RegExp(name, "i") },
{ body: new RegExp(name, "i") },
{},
]).limit(10).exec(function (err, docs) {
if (err){
response.json('error', err)
}
else{
response.json('info', docs)
}
})
Thank you for advance!
First point, to search for a match within an array is identical to searching a plain string. Mongo is smart enough to see that the property is an array and search it's content. ...
Dishes.find({steps: new RegExp(name, "i")})
... will work as you would hope/expect.
Second point, for comments, ingredients, categories, your schema is designed with separate collections interreferenced by ObjectId. Mongo cannot do joins like a relational database, so your query above will never match anything. Any given mongo operation is going to look in one and only one collection. You'll need to search each collection separately and then find the corresponding Dish records, or redesign your schema to use nested documents instead of references.