Search code examples
mongodbmongoose

How to find string in array using Mongoose?


I have a schema through mongoose:

const mongoose = require('mongoose');

const recipeSchema = mongoose.Schema({

title: String,
chef: String,
updated: {type: Date, default: Date.now},
region: String,
ingredients: [String],
instructions: [String]
}, { collection: 'recipes' })

module.exports = mongoose.model('Recipes', recipeSchema);

I find the mongoose docs really difficult to understand. I am trying to search for a match of all substring within the 'ingredients' array. I read somewhere that it could be done like so:

 .find({ingredients: 'ing1'}) // not working

 .find({'ing1': {$in: ingredients}})  // not working

I find it pretty difficult to find in depth tutorials on mongoose as well. Im thinking about not using it at all anymore and just sticking to mongodb shell.


Solution

  • You can use a regex search to match substrings:

    .find({ingredients: /ing1/})